Finding the cause for deadlock in multi threading?

淺唱寂寞╮ 提交于 2019-12-21 05:31:22

问题


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:


  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.




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!