Thread Deadlock Detection in Java
Thread deadlock relates to the multitasking. When two threads have circular dependency on a synchronized, deadlock is possible.
In other words, a situation where a thread is waiting for an object lock that holds by second thread, and this second thread is waiting for an object lock that holds by first thread, this situation is known as Deadlock.
Example
In the given below example, we have created two classes X & Y. They have methods foo() & bar() respectively. they pause for a short period before trying to invoke a method in the other class.
In this example, you will see that while waiting for the monitor on x ,RacingTread have monitor on y. Simultaneously, MainThread have x and is waiting for y. This program will never complete. Means it will have a deadlock
class X { synchronized void foo(Y y) { String name = Thread.currentThread().getName(); System.out.println(name + " entered X.foo"); try { Thread.sleep(1000); } catch(Exception e) { System.out.println("X Interrupted"); } System.out.println(name + " trying to call Y.last()"); y.last(); } synchronized void last() { System.out.println("Inside X.last"); } } class B { synchronized void bar(X x) { String name = Thread.currentThread().getName(); System.out.println(name + " entered Y.bar"); try { Thread.sleep(1000); } catch(Exception e) { System.out.println("Y Interrupted"); } System.out.println(name + " trying to call Y.last()"); x.last(); } synchronized void last() { System.out.println("Inside X.last"); } } class Deadlock implements Runnable { X x= new X(); Y y= new Y(); Deadlock() { Thread.currentThread().setName("MainThread"); Thread t = new Thread(this, "RacingThread"); t.start(); x.foo(y); // get lock on a in this thread. System.out.println("Back in main thread"); } public void run() { b.bar(x); // get lock on b in other thread. System.out.println("Back in other thread"); } public static void main(String args[]) { new Deadlock(); } }
Output
MainThread entered X.foo RacingThread entered Y.bar MainThread trying to call Y.last() RacingThread trying to call X.last() |
Deadlock Prevention
Given below the three techniques to prevent your code from deadlock :
Lock ordering
In this technique all locks are obtained in the same sequence by any thread. This way you can prevent deadlock occurrence.
Lock Timeout
If a thread doesn't succeed in taking all the necessary locks within a certain amount of time period, it will realease all the locks held by it. And again try after a random time.
Deadlock Detection
It is a heavy deadlock prevention technique. It is targeted to design to implement in the condition where Lock ordering and Lock timeout is not worked effectively.
In this technique, we use data structure(For example-map, graph etc) to note down the lock taken by a thread. Also the request by a thread for lock, is also note down into the data structure.
When ever a request for the lock is denied, the thread traverse the lock graph to check deadlock.