Java ThreadMXBean & 死锁检测

更多 Java 并发编程方面的文章,请参见文集《Java 并发编程》


ThreadMXBean 介绍

ThreadMXBean 在 java.lang.management 包中。
public interface ThreadMXBeanextends extends PlatformManagedObject

The management interface for the thread system of the Java virtual machine.
Java 虚拟机中线程系统的管理接口。
A Java virtual machine has a single instance of the implementation class of this interface.
每一个 Java 虚拟机 只有该接口的一个单独实例。
This instance implementing this interface is an MXBean that can be obtained by calling the ManagementFactory.getThreadMXBean()
method or from the platform MBeanServer method.
可以通过调用 ManagementFactory.getThreadMXBean() 方法或者 platform MBeanServer 方法获得。

ThreadMXBean 主要方法

  • ThreadInfo[] dumpAllThreads(boolean lockedMonitors, boolean lockedSynchronizers)

    • Returns the thread info for all live threads with stack trace and synchronization information.
  • long[] findDeadlockedThreads() 找到死锁的线程 ID

    • Finds cycles of threads that are in deadlock waiting to acquire object monitors or ownable synchronizers.
  • long[] findMonitorDeadlockedThreads() 找到死锁的线程 ID

    • Finds cycles of threads that are in deadlock waiting to acquire object monitors.
  • long[] getAllThreadIds() 找到所有存活状态的线程 ID

    • Returns all live thread IDs.
  • long getCurrentThreadCpuTime() 当前线程的总共 CPU 时间,单位为纳秒

    • Returns the total CPU time for the current thread in nanoseconds.
  • long getCurrentThreadUserTime() 当前线程的在 用户态 运行的总共 CPU 时间,单位为纳秒

    • Returns the CPU time that the current thread has executed in user mode in nanoseconds.
  • int getDaemonThreadCount() 守护线程的数量

    • Returns the current number of live daemon threads.
  • int getPeakThreadCount()

    • Returns the peak live thread count since the Java virtual machine started or peak was reset.
  • int getThreadCount() 线程的数量,包括守护线程和非守护线程

    • Returns the current number of live threads including both daemon and non-daemon threads.
  • long getThreadCpuTime(long id) 根据 ID 得到某一个线程的运行时间

    • Returns the total CPU time for a thread of the specified ID in nanoseconds.
  • long getThreadUserTime(long id)

    • Returns the CPU time that a thread of the specified ID has executed in user mode in nanoseconds.
  • ThreadInfo getThreadInfo(long id) 根据 ID 得到某一个线程的详细信息

  • Returns the thread info for a thread of the specified id with no stack trace.

ThreadInfo 介绍

ThreadInfo 在 java.lang.management 包中。
public class ThreadInfo extends Object

ThreadInfo 记录了一个线程的信息,包括

  • 基本信息

    • ID
    • Name
  • 运行信息

    • Thread state. 线程状态
    • The object upon which the thread is blocked due to: 如果该线程被阻塞,是哪个对象导致的
      • waiting to enter a synchronization block/method, or 等待进入 synchronization 代码块或方法
      • waiting to be notified in a Object.wait method, or 调用了 wait 方法,等待被 notify
      • parking due to a LockSupport.park call. LockSupport.park 调用
    • The ID of the thread that owns the object that the thread is blocked. 结合上面,该对象被哪一个线程锁定
    • Stack trace of the thread.
    • List of object monitors locked by the thread. 该线程锁定的对象
    • List of ownable synchronizers locked by the thread.

示例:

"Thread-2" Id=11 TIMED_WAITING (该线程的NAME, ID 及状态)
at java.lang.Thread.sleep(Native Method)
at DeadLockThread.run(DeadLockTesting.java:55) (该线程的stack trace)
locked java.lang.Object@1bd2664 (该线程锁定的对象)

使用 ThreadMXBean 检测死锁

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class DeadLockTesting {

    public static void main(String args[]) {
        Object obj1 = new Object();
        Object obj2 = new Object();

        DeadLockThread t1 = new DeadLockThread(obj1, obj2);
        DeadLockThread t2 = new DeadLockThread(obj2, obj1);

        t1.start();
        t2.start();

        try {
            Thread.sleep(2000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        MonitorThread mt = new MonitorThread();
        mt.start();
    }
}

class MonitorThread extends Thread {
    public void run() {
        ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
        long[] ids = tmx.findDeadlockedThreads();
        if (ids != null) {
            ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true);
            System.out.println("The following threads are deadlocked:");
            for (ThreadInfo ti : infos) {
                System.out.println(ti);
            }
        }
    }
}

class DeadLockThread extends Thread {
    private Object obj1;
    private Object obj2;

    public DeadLockThread(Object obj1, Object obj2) {
        this.obj1 = obj1;
        this.obj2 = obj2;
    }

    public void run() {
        synchronized (obj1) {
            try {
                Thread.sleep(1000);
                synchronized (obj2) {

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

结果:

"Thread-1" Id=10 BLOCKED on java.lang.Object@b0bad7 owned by "Thread-0" Id=9 (Thread-1 等待 Thread-0)
at DeadLockThread.run(DeadLockTesting.java:57)
blocked on java.lang.Object@b0bad7 (Thread-1 等待的对象)
locked java.lang.Object@1238bd2 (Thread-1 锁定的对象)

"Thread-0" Id=9 BLOCKED on java.lang.Object@1238bd2 owned by "Thread-1" Id=10 (Thread-0 等待 Thread-1)
at DeadLockThread.run(DeadLockTesting.java:57)
blocked on java.lang.Object@1238bd2 (Thread-0 等待的对象)
locked java.lang.Object@b0bad7 (Thread-0 锁定的对象)


引用:
https://docs.oracle.com/javase/7/docs/api/java/lang/management/ThreadMXBean.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,651评论 18 139
  • 个人笔记,方便自己查阅使用 Contents Java LangAssignment, ReferenceData...
    freenik阅读 1,382评论 0 6
  • 1.在C/C++中实现本地方法 生成C/C++头文件之后,你就需要写头文件对应的本地方法。注意:所有的本地方法的第...
    JayQiu阅读 2,361评论 0 3
  • 由来 what? DNS预获取,是前段优化的一部分 作用 减少用户的等待时间,提升用户体验。 浏览器支持 Fire...
    嘻哈章鱼小丸子阅读 528评论 0 0
  • 自信是一种气质,让你拥有更多机会。同样对话中,和自信的人与自卑的人对话,往往会更喜欢自信的人交流。自信的人虽然不能...
    飘渺_d65f阅读 513评论 0 0