Java — Deadlock | Code Factory

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.
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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store