Java Thread Deadlock

Deadlock is a special type of error that needs to be avoided in multitasking. This mainly occurs, when two threads have interdependency on a pair of synchronized objects.

 

class DLock

{

public static void main(String aa[])

{

//two resource objects for which we need to get locks are declared

final Object res1="First Resource";

final Object res2="Second Resource";

//This is the first thread. It first tries to lock resource1 then resource2

Thread thr1=new Thread()

{

public void run()

{

//Lock resource1

synchronized(res1)

{

System.out.println("First Thread locked first resource");

//Forcing deadlock to happen by pausing a bit

try

{

Thread.sleep(100);

}

catch(InterruptedException ie)

{

}

//Wait till we get a lock on resource2

synchronized(res2)

{

System.out.println("First Thread locked second resource");

}

}

}

};

//The second thread tries to lock reosurce2 then resource1

Thread thr2=new Thread()

{

public void run()

{

//this thread locks resource2 without any delay

synchronized(res2)

{

System.out.println("Second Thread:locked second resource");

//pauses like the first thread

try

{

Thread.sleep(100);

}

catch(InterruptedException iee)

{

}

/*The program freezes when the thread tries to lock resource1, as thread1 has locked resource1 and shall not release it till it gets a lock on resource2. This thread holds lock on resource2 and shall not release it till gets resource1*/

synchronized(res1)

{

System.out.println("Second Thread first resource");

}

}

}

};

//starts the two threads.Deadlock occurs, and the program never exits

thr1.start();

thr2.start();

}

}

Deadlock in Java

Explanation…

In this example....

A deadlock is created between two threads that are trying to acquire locks on two different resources. In order to avoid this type of deadlock when locking multiple resources, all the threads should acquire locks in the same order.