java中的编程死锁检测 [英] Programmatic deadlock detection in java

查看:24
本文介绍了java中的编程死锁检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何以编程方式检测到 Java 程序中发生了死锁?

How can I programmatically detect that a deadlock has occurred in a Java program?

推荐答案

您可以使用 JDK 附带的 ThreadMXBean 以编程方式执行此操作:

You can do this programmatically using the ThreadMXBean that ships with the JDK:

ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long[] threadIds = bean.findDeadlockedThreads(); // Returns null if no threads are deadlocked.

if (threadIds != null) {
    ThreadInfo[] infos = bean.getThreadInfo(threadIds);

    for (ThreadInfo info : infos) {
        StackTraceElement[] stack = info.getStackTrace();
        // Log or store stack trace information.
    }
}

显然,您应该尝试隔离执行此死锁检查的线程 - 否则,如果该线程死锁,它将无法运行检查!

Obviously you should try to isolate whichever thread is performing this deadlock check - Otherwise if that thread deadlocks it won't be able to run the check!

顺便说一下,这就是 JConsole 在幕后使用的东西.

Incidentally this is what JConsole is using under the covers.

这篇关于java中的编程死锁检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆