Deadlock in Java Multithreading
Deadlock in Java multithreading is a special type of error. It occurs when two threads have circular dependency on a pair of synchronized objects. Consider the following case:
Two threads enter the monitor on objects X and Y respectively. If the thread in X calls synchronized method on Y, it will block it. However, when thread in Y calls synchronized method in X, it would have to release its own lock on Y so that first thread could complete. Hence the thread waits forever. This is called a deadlock. It may include more than two threads and synchronized objects also.
Deadlocks are difficult to debug because:
- It occurs when two threads time-slice in just the right way
- It might contain more than two threads and more than two synchronized objects. This means that ot can occur through a more convoluted sequence of events.
Demonstration of deadlock in Java Multithreading
class A
{
synchronized void f1(B b)
{
System.out.println(name+" entered A.f1");
try
{
Thread.sleep(1000);
}catch(Exception e){
System.out.println("A interrupted ");
}
System.out.println(name+" trying to call B.last() ");
b.last();
}
synchronized void last()
{
System.out.println("Inside A.last");
}
}
class B
{
synchronized void f2(A a)
{
String name=Thread.currentThread().getName();
System.out.println(name+" entered B.f2");
try{
Thread.sleep(1000);
}catch(Exception e){
System.out.println("B interrupted");
}
System.out.println(name+" trying to call A.last()");
a.last();
}
synchronized void last()
{
System.out.println("Inside A.last");
}
}
class deadlock implements Runnable{
A a=new A();
B b =new B();
deadlock(){
Thread.currentThread().setName("MainThread");
Thread t = new Thread(this, "RunningThread");
t.start();
a.f1(b);
System.out.println("Back in main thread");
}
public void run(){
b.f2(a);
System.out.println("Back in other thread");
}
public static void main(String args[]){
new deadlock();
}
}Output:
MainThread entered A.f1 RunningThread entered B.f2 MainThread trying to call B.last() RuuningThread trying to call A.last()
Leave a Reply