Sunday, 5 February 2012

Deadlock in Java Thread

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Here's an example.
Ramesh and Suresh are employees of a Bank.Before leaving the office ,they have to check each other's work .But one condition is that, both of them can't do the review at the same time.


class Employee {

synchronized void doWork(Employee neighbour) {
System.out.println(Thread.currentThread().getName() + " started work");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ " waiting.... for checking neighbours work");
neighbour.verifyNeighboursWork();
}


synchronized void verifyNeighboursWork() {
System.out.println(Thread.currentThread().getName()
+ " Checked Neighbours work");
}

}

class Task extends Thread {
Employee emp;
Employee neighbour;

Task(Employee emp, Employee neighbour) {
this.emp = emp;
this.neighbour = neighbour;
}

public void run() {
emp.doWork(neighbour);
}
}

public class Main {
public static void main(String args[]) throws InterruptedException {

final Employee ramesh = new Employee();
final Employee suresh = new Employee();
Task rameshTask = new Task(ramesh, suresh);
rameshTask.setName("Ramesh");
Task sureshTask = new Task(suresh, ramesh);
sureshTask.setName("Suresh");
rameshTask.start();
sureshTask.start();

}

}

The output is

Ramesh started work
Suresh started work
Ramesh waiting.... for checking neighbours work
Suresh waiting.... for checking neighbours work

The above program never terminates.The reason is Ramesh waiting for Suresh to finish and vice versa.This leads to a deadlock situation.

JConsole Screen-Shots

The following screen-shots describe the above mentioned deadlock situation.

(NOTE: Click on the image to enlarge it)



No comments:

Post a Comment