Deadlock

  1. If two threads are waiting for each other for ever such type of infinite waiting is called dead lock.
  2. Synchronized keyword is the only keyword for deadlock situation.Hence when using synchronized keyword we have to take special care.
  3. There are no resolution technique for deadlock, but several prevention technique are available.

Below example shows a demo of dead lock

package com.demo4;

public class DeadLock extends Thread {
	A a = new A();
	B b = new B();
	public void execute() throws InterruptedException {
		System.out.println("Started execute");
		this.start();
		System.out.println("Continuing execution of main method");
		a.d1(b);
	}
	public void run() {
		try {
			System.out.println("Started run of child thread");
			b.d2(a);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) throws InterruptedException {
		System.out.println("Started main");
		DeadLock deadlock = new DeadLock();
		deadlock.execute();
	}
}
class A{
	public synchronized void d1(B b)  throws InterruptedException {
		Thread.sleep(10000);
		System.out.println("Going to execute last method of B");
		b.last();

	}
	public synchronized void last() {
		System.out.println("Executing last of A class");
	}
}
class B{
	public synchronized void d2(A a) throws InterruptedException {
		Thread.sleep(10000);
		System.out.println("Going to execute last method of A");
		a.last();
	}
	public synchronized void last() {
		System.out.println("Executing last of B class");
	}

}

In the above program if we remove atleast one synchronized keyword then the program won’t enter into deadlock state.Hence synchronized keyword is the only reason for deadlock situation. Due to this while using synchronized keyword we have to consider this situation.

Dead lock vs Starvation

Long waiting of a thread where waiting never ends is called Deadlock.
Various long waiting of thread where waiting ends at certain point is called starvation.
For example : Low priority has to wait unit completing all high priority threads. It may be long waiting but ends at certain point, which is nothing but starvation..

Example on Deadlock using join() method (Good Example of join)

public class DeadLockDemo {
	public static void main(String[] args) throws InterruptedException {
		MyThread t = new MyThread(Thread.currentThread());
		t.start();
		System.out.println("Main Thread waiting for Child Thread to be completed");
		t.join();
	}
}
class MyThread extends Thread{
	Thread t;
	MyThread(Thread t){
		this.t = t;
	}
	public void run() {
		try {
			System.out.println("Child Thread waiting for main thread to be completed");
			t.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

Leave a Comment