java中的程序化死锁检测

时间:2009-07-09 07:30:57

标签: java multithreading concurrency deadlock

如何以编程方式检测Java程序中是否发生了死锁?

9 个答案:

答案 0 :(得分:60)

您可以使用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在幕后使用的内容。

答案 1 :(得分:11)

调查的一个有用提示:

如果您可以抓住应用程序并且怀疑发生了死锁,请在java.exe控制台窗口(或Solaris / Linux上的“Ctrl- \”)中按“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)
    ...

答案 2 :(得分:4)

您可以使用ThreadMXBean类以编程方式检测死锁线程。这是代码,

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

单击here以获取有关如何检测死锁线程的更多信息。

答案 3 :(得分:3)

JArmus是一个用于死锁检测和避免的库。它包括支持: Thread.joinCyclicBarrierCountDownLatchPhaserReentrantLock

要使用JArmus,您需要检测代码。通过其中一个仪表类或自动使用JArmus乐器jarmusc

java -jar jarmusc.jar yourprogram.jar checkedprogram.jar

输入yourprogram.jar是您要检查的程序。 输出是相同的程序,检查自动查找任何死锁。

障碍需要一些帮助

使用类CyclicBarrierCountDownLatchPhaser验证死锁有点棘手 - 例如,JConsole无法检测到这些类型的死锁。 JArmus需要您的帮助:您必须指定哪些线程影响同步,我们称之为已注册的线程。

线程必须尽快将自己标记为已注册。标记已注册线程的好地方是开始方法Runnable.run JArmus.register(latch);

实施例

以下程序可以正确识别死锁 JArmus:

final CountDownLatch latch = new CountDownLatch(2);
final CyclicBarrier barrier = new CyclicBarrier(2);
final Queue<Exception> exceptions = new ArrayDeque<>();
Thread t1 = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            JArmus.register(barrier); // do not forget to register!
            JArmus.register(latch); // do not forget to register!
            latch.countDown();
            latch.await();
            barrier.await();
        } catch (Exception e) {
            exceptions.add(e);
        }
    }
});
Thread t2 = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            JArmus.register(barrier); // do not forget to register!
            JArmus.register(latch); // do not forget to register!
            barrier.await();
            latch.countDown();
            latch.await();
        } catch (Exception e) {
            exceptions.add(e);
        }
    }
});
t1.start();
t2.start();

答案 4 :(得分:2)

您可能需要考虑IBM's MTRAT。毕竟预防胜于治疗。 Multicore Software Development Kit还附带了死锁检测工具。

答案 5 :(得分:2)

如果您不需要程序检测,可以通过 JConsole ;在线程选项卡上有一个“检测死锁”按钮。在JDK6中,这将检测内部监视器和j.u.c Lock s

的锁定

通过$JAVA_HOM/bin/jconsole命令

运行JConsole

答案 6 :(得分:1)

tempus-fugit还与程序化线程转储类一起实现它。它是使用上面提到的mbean机制实现的,并且提供了一种开箱即用的超级终极解决方案。

答案 7 :(得分:1)

这里有代码:http://www.java2s.com/Code/Java/Development-Class/PerformingdeadlockdetectionprogrammaticallywithintheapplicationusingthejavalangmanagementAPI.htm

神奇发生在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;
  }

这会调用ThreadMXBean的API,它在Java 5和6中具有不同的名称(因此外部if())。

代码示例还允许中断锁定,因此您甚至可以打破死锁。

答案 8 :(得分:0)

如果您希望在运行时完成此操作,可以使用watchdog