Programmatic deadlock detection in java

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

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

9条回答
  •  半阙折子戏
    2020-11-29 18:09

    You can detect the deadlocked threads programmatically using ThreadMXBean class.Here is the code,

        ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    
        long ids[] = bean.findMonitorDeadlockedThreads();
    
        if(ids != null)
        {
            ThreadInfo threadInfo[] = bean.getThreadInfo(ids);
    
            for (ThreadInfo threadInfo1 : threadInfo)
            {
                System.out.println(threadInfo1.getThreadId());    //Prints the ID of deadlocked thread
    
                System.out.println(threadInfo1.getThreadName());  //Prints the name of deadlocked thread
    
                System.out.println(threadInfo1.getLockName());    //Prints the string representation of an object for which thread has entered into deadlock.
    
                System.out.println(threadInfo1.getLockOwnerId());  //Prints the ID of thread which currently owns the object lock
    
                System.out.println(threadInfo1.getLockOwnerName());  //Prints name of the thread which currently owns the object lock.
            }
        }
        else
        {
            System.out.println("No Deadlocked Threads");
        }
    

    Click here for more info on how to detect the deadlocked threads.

提交回复
热议问题