Search code examples
javamultithreadingconcurrencydeadlock

Finding the cause for deadlock in multi threading?


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 ?


Solution

    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.