Programmatic deadlock detection in java

前端 未结 9 1378
无人及你
无人及你 2020-11-29 17:36

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

9条回答
  •  -上瘾入骨i
    2020-11-29 18:17

    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!

    Incidentally this is what JConsole is using under the covers.

提交回复
热议问题