Deadlock in Thread

A deadlock is a situation where a thread is waiting for an object lock that another thread holds, and this second thread is waiting for an object lock that the first thread holds. Since each thread is waiting for the other thread to relinquish a lock, they both remain waiting forever in the Blocked-for-lock-acquisition state. The threads are said to be deadlocked.

Let’s say Thread t1 has a lock on object o1, but cannot acquire the lock on object o2. Thread t2 has a lock on object o2, but cannot acquire the lock on object o1. They can only proceed if one of them relinquishes a lock the other one wants, which is never going to happen.

package com.blog;

public class Deadlock {

String o1 = “Dead”;
String o2 = “Lock”;

Thread t1 = new Thread(“Thread1″){
public void run(){
while(true){
synchronized(o1){
synchronized(o2){
System.out.println(o1 +” “+ o2);
}
}
}
}
};

Thread t2 = new Thread(“Thread2″){
public void run(){
while(true){
synchronized(o2){
synchronized(o1){
System.out.println(o2 +” “+ o1);
}
}
}
}
};

public static void main(String a[]){
Deadlock dl = new Deadlock();
dl.t1.start();
dl.t2.start();
}
}

Output
Dead Lock
Dead Lock
Dead Lock
Dead Lock
Dead Lock
……Then the application hangs for ever unless you quit it forcefully

Avoiding deadlock: One of the best ways to prevent the potential for deadlock is to avoid acquiring more than one lock at a time, which is often practical. However, if that is not possible, you need a strategy that ensures you acquire multiple locks in a consistent, defined order. 

In our example, keeping a consistent defined order resolves the deadlock.

package com.blog;

public class Deadlock {

String o1 = “Dead”;
String o2 = “Lock”;

Thread t1 = new Thread(“Thread1″){
public void run(){
while(true){
synchronized(o1){
synchronized(o2){
System.out.println(o1 +” “+ o2);
}
}
}
}
};

Thread t2 = new Thread(“Thread2”){
public void run(){
while(true){
synchronized(o1){//Changed order of locks
synchronized(o2){
System.out.println(o2 +” “+ o1);
}
}
}
}
};

public static void main(String a[]){
Deadlock dl = new Deadlock();
dl.t1.start();
dl.t2.start();
}
}

Output
Dead Lock
Dead Lock
Dead Lock
Dead Lock
Dead Lock
Dead Lock
…..
Lock Dead
Lock Dead
Lock Dead
Lock Dead
Lock Dead
…..
Dead Lock
Dead Lock
Dead Lock
Dead Lock
Dead Lock
Dead Lock
…..

Leave a Reply

Your email address will not be published. Required fields are marked *