Thread Deadlock


A Thread Deadlock occurs when two (or more) threads are "waiting" for each other to release a lock, resulting in an infinite wait time.

Consider this as an example of a Thread Deadlock:

If a thread t1 has acquired a lock on class A object "a" and wants to acquire lock on class B object "b" and another thread t2 has acquired a lock on class B object "b" and at the same time wants to acquire a lock on class A object "a". In this situation,  one thread is waiting for another thread to release the resource. This waiting continues indefinitely and this situation is called a Thread Deadlock.

The following example demonstrates a thread deadlock:

class A {
	public synchronized void m1(B b) {
		b.m2(this);
	}
}

class B {
	public synchronized void m2(A a) {
		a.m1(this);
	}
}

class Thread1 extends Thread {
	A a;
	B b;

	Thread1(A a, B b) {
		this.a = a;
		this.b = b;
	}

	public void run() {
		a.m1(b);
	}
}

class Thread2 extends Thread {
	A a;
	B b;

	Thread2(A a, B b) {
		this.a = a;
		this.b = b;
	}

	public void run() {
		b.m2(a);
	}
}

public class DeadLockDemo {
	public static void main(String[] args) {
		A a = new A();
		B b = new B();
		Thread1 t1 = new Thread1(a, b);
		Thread2 t2 = new Thread2(a, b);
		t1.start();
		t2.start();
	}
}

No thread would be able to execute as thread1 and thread2 are waiting for each other to release the resource.