If two threads are waiting for each other forever such type of infinite waiting is known as deadlock
the synchronized keyword is the only reason for the deadlock situation. Hence while using synchronized keywords we have to take special care. Since there is no resolution technique for deadlock but several techniques for deadlock prevention is available.
Deadlock in Java Example
class A{
public synchronized void method1( B b){
System.out.println("Thread 1 started the execution of method1");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
System.out.println("Thread 1 is trying to call class B last method");
b.last();
}
public synchronized void last()
{
System.out.println("Inside class A last method");
}
}
class B{
public synchronized void method2(A a) {
System.out.println("Thread 2 started the execution of method2");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
System.out.println("Thread 2 is trying to call class A last method");
a.last();
}
public synchronized void last()
{
System.out.println("Inside class B last method");
}
}
public class DeadLock extends Thread{
A a = new A();
B b = new B();
public void method() {
this.start();
a.method1(b);
}
@Override
public void run() {
b.method2(a);
}
public static void main(String[] args) {
DeadLock d = new DeadLock();
d.method();
}
}
In the above java Program if we removed at least one synchronized keyword then the program would not enter into a deadlock condition. Hence synchronized keyword is the only reason for the deadlock condition/situation, due to this while working with synchronized keywords we have to take special care.