Java中的死锁检测 [英] Deadlock detection in Java
问题描述
很久以前,我从Java参考书中保存了一句话:Java没有处理死锁的机制。它甚至不知道发生了死锁。 (Head First Java 2nd Edition,p.516)
Long time ago, I saved a sentence from a Java reference book: "Java has no mechanism to handle deadlock. it won't even know deadlock occurred." (Head First Java 2nd Edition, p.516)
那么,它是什么呢?有没有办法在Java中捕获死锁案例?我的意思是,有没有一种方法可以让我们的代码理解发生死锁的情况?
So, what is about it? Is there a way to catch deadlock case in Java? I mean, is there a way that our code understands a deadlock case occurred?
推荐答案
从JDK 1.5开始,有非常有用的方法 java.lang.management
包,用于查找和检查发生的死锁。查看 ThreadMXBean的
class。 findMonitorDeadlockedThreads()
和 findDeadlockedThreads()
方法
Since JDK 1.5 there are very useful methods in the java.lang.management
package to find and inspect deadlocks that occurs. See the findMonitorDeadlockedThreads()
and findDeadlockedThreads()
method of the ThreadMXBean
class.
使用它的一种可能方法是使用单独的监视程序线程(或定期任务)来执行此操作。
A possible way to use this is to have a separate watchdog thread (or periodic task) that does this.
示例代码:
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);
}
}
这篇关于Java中的死锁检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!