Deadlock detection in Java

后端 未结 16 1072
野的像风
野的像风 2020-11-28 20:21

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 E

16条回答
  •  清歌不尽
    2020-11-28 20:49

    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.

    Sample code:

      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);
         }
      }
    

提交回复
热议问题