5

A multi threaded application freezes. Perhaps it was caused by a deadlock. If yes, then how do we find the cause for the deadlock ? Any tools and strategies for doing this systematically ?

david blaine
  • 5,683
  • 12
  • 46
  • 55

3 Answers3

8
  1. When possible, use a lock-free data structure like a ConcurrentLinkedQueue. By definition, a lock-free data structure cannot cause a deadlock.

  2. Always acquire locks in the same order. If your resources are A, B, and C, then all threads should acquire them in the order of A -> B -> C, or A -> C, or B -> C, etc. Deadlock can occur if one thread acquires them in the order A -> B -> C while another thread acquires them in the order C -> B -> A.

  3. Use lock timeouts - if a timer expires then a thread releases its locks. Be sure to log when this occurs so that you can re-examine your lock ordering.

  4. Use deadlock detection.

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
  • 1
    All good ideas, but none of them answers the question: How to find the bug in an existing program. As Boris the Spider, Vishal K., and Don said, if you can catch it while the JVM still is hung, you can use various tools to find out which threads are waiting for which locks. That information usually will lead you to the root cause. (often your #2, above). – Solomon Slow Oct 01 '14 at 12:54
7

How do we find the cause for the deadlock ?

  • Using Program

java.lang.management.ThreadMXBean is the answer to find out deadlock threads in Java. Here is the short code demo:

import java.lang.management.*;
class  DeadLockDetect
{
    public void findDeadLocks()
    {
        ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
        long[] ids = tmx.findDeadlockedThreads();
        if (ids != null )
        {
            ThreadInfo[] infos = tmx.getThreadInfo(ids,true,true);
            System.out.println("Following Threads are deadlocked");
            for (ThreadInfo info : infos)
            {
                System.out.println(info);
            }
        }
    }
}
  • Using Tool
    JConsole is one of the tools that tells almost all information about the threads running in your code.
Community
  • 1
  • 1
Vishal K
  • 12,976
  • 2
  • 27
  • 38
5

The first thing I would do is to fetch the thread stack with jstack, which comes with the JDK.

Usage : jstack <pid>

Here you can see the current state of all threads running. You can see threads waitung for locks etc.

Doc : http://docs.oracle.com/javase/1.5.0/docs/tooldocs/share/jstack.html

Here you can see what different threads states exist : http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.State.html

Don
  • 1,134
  • 8
  • 15