Java 中的编程死锁检测
2022-08-31 15:12:38
如何以编程方式检测 Java 程序中是否发生了死锁?
如何以编程方式检测 Java 程序中是否发生了死锁?
您可以使用 JDK 附带的 编程方式执行此操作:ThreadMXBean
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.
}
}
显然,您应该尝试隔离正在执行此死锁检查的任何线程 - 否则,如果该线程死锁,它将无法运行检查!
顺便说一句,这就是JConsole在幕后使用的东西。
一个有用的调查提示:
如果您可以抓住应用程序并怀疑发生了死锁,请在java.exe控制台窗口中按“Ctrl-Break”(或在Solaris/Linux上按“Ctrl-Break”)。jvm将转储所有线程的当前状态和堆栈跟踪,找出死锁并精确描述它们。
它看起来像这样:
Full thread dump Java HotSpot(TM) Client VM (1.5.0_09-b03 mixed mode):
"[Test Timer] Request Queue" prio=6 tid=0x13d708d0 nid=0x1ec in Object.
wait() [0x1b00f000..0x1b00fb68]
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Unknown Source)
at library.util.AsyncQueue.run(AsyncQueue.java:138)
- locked <0x02e70000> (a test.server.scheduler.SchedulerRequestQueue)
...
Found one Java-level deadlock:
=============================
"Corba service":
waiting to lock monitor 0x13c06684 (object 0x04697d90, a java.lang.Object),
which is held by "[Server Connection] Heartbeat Timer"
"[Server Connection] Heartbeat Timer":
waiting to lock monitor 0x13c065c4 (object 0x0467e728, a test.proxy.ServerProxy), which is held by "Corba service"
Java stack information for the threads listed above:
===================================================
"Corba service":
at test.proxy.ServerProxy.stopHBWatchDog(ServerProxy:695)
- waiting to lock <0x04697d90> (a java.lang.Object)
...