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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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