Programmatic deadlock detection in java

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

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

9条回答
  •  佛祖请我去吃肉
    2020-11-29 18:01

    There is code here: http://www.java2s.com/Code/Java/Development-Class/PerformingdeadlockdetectionprogrammaticallywithintheapplicationusingthejavalangmanagementAPI.htm

    The magic happens in ThreadMonitor.findDeadlock():

      public boolean findDeadlock() {
        long[] tids;
        if (findDeadlocksMethodName.equals("findDeadlockedThreads")
            && tmbean.isSynchronizerUsageSupported()) {
          tids = tmbean.findDeadlockedThreads();
          if (tids == null) {
            return false;
          }
    
          System.out.println("Deadlock found :-");
          ThreadInfo[] infos = tmbean.getThreadInfo(tids, true, true);
          for (ThreadInfo ti : infos) {
            printThreadInfo(ti);
            printLockInfo(ti.getLockedSynchronizers());
            System.out.println();
          }
        } else {
          tids = tmbean.findMonitorDeadlockedThreads();
          if (tids == null) {
            return false;
          }
          ThreadInfo[] infos = tmbean.getThreadInfo(tids, Integer.MAX_VALUE);
          for (ThreadInfo ti : infos) {
            // print thread information
            printThreadInfo(ti);
          }
        }
    
        return true;
      }
    

    This calls an API of the ThreadMXBean which has a different name in Java 5 and 6 (hence the outer if()).

    The code example also allows to interrupt the locks, so you can even break the deadlock.

提交回复
热议问题