问题
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 ?
回答1:
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.
Use deadlock detection.
回答2:
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.
回答3:
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
来源:https://stackoverflow.com/questions/15936725/finding-the-cause-for-deadlock-in-multi-threading