Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Thursday, August 4, 2011

Deadlock via Threads sample

A sample demonstration of deadlock.
Here it goes.

public class DeadlockSample {

public static void main(String[] args) {
final DeadlockSample d = new DeadlockSample();
final DeadlockSample d1 = new DeadlockSample();
Thread t1 = new Thread() {
public void run() {
System.out.println("Thread t1 before entering synchronized block d");
synchronized (d) {
System.out.println("Thread 1: locked d");

try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
System.out.println("Thread t1 before entering synchronized block d1");
synchronized (d1) {
System.out.println("Thread 1: locked d1");
}
}
}
};

Thread t2 = new Thread() {
public void run() {
System.out.println("Thread t2 before entering synchronized block d1");
synchronized (d1) {
System.out.println("Thread 2: locked d1");

try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
System.out.println("Thread t2 before entering synchronized block d");
synchronized (d) {
System.out.println("Thread 2: locked d");
}
}
}
};
t1.start();
t2.start();
}
}

On execution,

Thread t1 before entering synchronized block d
Thread 1: locked d
Thread t2 before entering synchronized block d1
Thread 2: locked d1
Thread t1 before entering synchronized block d1
Thread t2 before entering synchronized block d

and the program goes into a deadlock. Each Thread waits for the other to complete.

No comments: