Java — Deadlock | Code Factory

Code Factory
2 min readJun 2, 2020

--

Index Page : Link

Donate : Link

WordPress Blog : Link

  • If 2 threads are waiting for each other forever, such type of infinite waiting is called Deadlock.
  • Synchronized keyword is only reason for deadlock situation, hence while using Synchronized keyword we have to take special care.
  • There are no resolution technique for deadlock but several prevantion technique are available.
package com.example.thread;/**
* @author code.factory
*
*/
public class DeadlockTest extends Thread {
A a = new A();
B b = new B();

public void m1() {
this.start();
a.a1(b); // This line executed by main Thread
}

public void run() {
b.b1(a); // This line executed by child thread
}

public static void main(String... args) {
DeadlockTest d = new DeadlockTest();
d.m1();
}
}
class A {
public synchronized void a1(B b) {
System.out.println("Thread1 start execution of a1 method");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread1 trying to call B's test()");
b.test();
}

public synchronized void test() {
System.out.println("Inside A's test() method");
}
}
class B {
public synchronized void b1(A a) {
System.out.println("Thread2 start execution of b1 method");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread2 trying to call A's test()");
a.test();
}

public synchronized void test() {
System.out.println("Inside B's test() method");
}
}

Output :

Thread1 start execution of a1 method
Thread2 start execution of b1 method
Thread2 trying to call A's test()
Thread1 trying to call B's test()
  • In the above program if we remove atleast one synchronized keyword then program wouldn’t entered into deadlock. Hence synchronized keyword is only reason for deadlock situation. So due to this while using synchronized keyword we have to take special care.
  • Long waiting of a Thread where waiting never ends is called deadlock.
  • Whereas long waiting of a Thread where waiting ends at certain point is called starvation.
  • Ex. Law priority Thread has to wait until completing all high priority threads. It may be long waiting but ends at certain point which is nothing but starvation.

--

--