java | thread deadlock example

// An example of deadlock.
// situation comes due to synchronized keyword

class A {
 synchronized void foo(B b) {
String name = Thread.currentThread().getName();   //main thread

System.out.println(name + " entered A.foo");

try {
  Thread.sleep(1000);      //suspended for 1 second
} catch(Exception e) {
  System.out.println("A Interrupted");
}

System.out.println(name + " trying to call B.last()");
b.last();                        //but b is locked by Racing thread
             // solution is use this.last();
 }

 synchronized void last() {
System.out.println("Inside A.last");
 }
}

class B {
 synchronized void bar(A a) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered B.bar");

try {
  Thread.sleep(1000);
} catch(Exception e) {
  System.out.println("B Interrupted");
}

System.out.println(name + " trying to call A.last()");
a.last();          //and here a is locked by main thread and situation comes called            
                                  //Deadlock

 }

 synchronized void last() {
System.out.println("Inside A.last");
 }
}

class Deadlock implements Runnable {
 A a = new A();       // say a address is 1000
 B b = new B();         // say b address is 2000

 Deadlock() {
            //There are two threads
Thread.currentThread().setName("MainThread");  / /first
Thread t = new Thread(this, "Racing Thread");       //second
t.start();//calling of run method for racing thread but after main thread

a.foo(b); // get lock on a by  main thread. and passing b’s reference
System.out.println("Back in main thread");
 }

 public void run()
{
b.bar(a);              // get lock on b in by racing thread.
System.out.println("Back in another thread");

 }


 public static void main(String args[]) {
new Deadlock();
 }

}

Reactions:

0 comments:

Post a Comment