Tuesday, July 29, 2008

Deadlock - what's it? How to deal with this situation?

Deadlock - what's it? How to deal with a Deadlock situation?

What's Deadlock?

It's basically a situation where two or more threads are blocked forever waiting for each other to release an acquired monitor to proceed further.

Let me try to explain it using an example. Suppose we have two thread - threadA and threadB. There are two objects of a class TestClass - objA and objB and we have two synchronized instance methods in TestClass named A and B. Method A accepts an argument of type TestClass and calls method B from the passed object reference. Now, consider a situation where the first thread - threadA acquires the monitor of objA and enteres into the synchronized method A() on objA with the passed object reference as objB and at the same time threadB enteres into the same synchronized method 'A' on the object reference - objB with the passed object reference to the method as objA. Now, both the threads will keep waiting for the monitors of the objects - objB and objA respectively to complete the execution of the synchronized method A() and hence such a situation will result into a Deadlock. Of course such a situation will probably happen only rarely, but it's definitely a possible scenario. Calling the start() method on a Thread instance only ensures that the particular thread will participate in the CPU Scheduling, but we never know when exactly the thread will actually be allocated the CPU and in turn will start the execution.

Example: Java program having a possibility of Deadlock

public class PossibleDeadlockDemo {

static class TestClass {



public synchronized void A (TestClass testClass) {




public synchronized void B () {




public static void main(String[] args) {

final TestClass objA = new TestClass("ObjectA");

final TestClass objB = new TestClass("ObjectB");

Thread threadA = new Thread(new Runnable() {

public void run() { objA.A(objB); } });

Thread threadB = new Thread(new Runnable() {

public void run() { objB.A(objA); } });





How to deal with a Deadlock situation?

Probably the only possible way to rectify a Deadlock situation is to avoid it. Once the deadlock has already happened then you'll probably left with the only option of restarting the JVM process again OR it may even require you to restart the underlying OS. This is very hard to reproduce and debug because one can never be sure about when exactly the threads will be executed and hence the deadlock may not happen when you test it and eventually it may happen when the code actually goes into production. So, review the design of your mulithreaded application before you really start coding. You may somehow manage to escape any such situation or at least minimize the possibility to a great extent with a better design.


No comments: