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 ?
-
Have a look at: http://stackoverflow.com/questions/1102359/programmatic-deadlock-detection-in-java There is a thread dealing with this. – Menelaos Apr 10 '13 at 21:31
-
Take a thread dump and see if there is a deadlock somewhere. – Boris the Spider Apr 10 '13 at 21:32
-
@andre - how does one make a graph of resource usage ? – david blaine Apr 10 '13 at 21:33
3 Answers
When possible, use a lock-free data structure like a ConcurrentLinkedQueue. By definition, a lock-free data structure cannot cause a deadlock.
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.
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.

- 17,888
- 4
- 41
- 69
-
1All 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
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.
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

- 1,134
- 8
- 15