Dead lock

Dead lock
  • If two Threads are waiting for each other forever(without end) such type of situation(infinite waiting) is called dead lock.
  • There are no resolution techniques for dead lock but several prevention(avoidance) techniques are possible.
  • Synchronized keyword is the cause for deadlock hence whenever we are using synchronized keyword we have to take special care.
package com.ashok.threads;

/**
 * 
 * @author ashok.mariyala
 *
 */
class Ashok {
   synchronized void foo(Vinod vinod) {
      System.out.println("Thread 1 entered foo() method");
      try {
         Thread.sleep(600);
      } catch (InterruptedException e) {
   }
      System.out.println("Thread 1 is trying to call vinod.last()");
      vinod.last();
   }

   synchronized void last() {
      System.out.println("Inside Ashok, This is last() method");
   }
}

class Vinod {
   synchronized void bar(Ashok ashok) {
      System.out.println("Threas 2 entered bar() method");
      try {
         Thread.sleep(600);
      } catch (InterruptedException e) {
      }
      System.out.println("Thread 2 is trying to call ashok.last()");
      ashok.last();
   }

   synchronized void last() {
      System.out.println("Inside Vinod, This is last() method");
   }
}

public class MyDeadLock implements Runnable {
   Ashok ashok = new Ashok();
   Vinod vinod = new Vinod();

   MyDeadLock() {
      Thread t = new Thread(this);
      t.start();
      vinod.bar(ashok);
   }

   public void run() {
      ashok.foo(vinod);
   }

   public static void main(String arg[]) {
      new MyDeadLock();
   }
}

Output

Threas 2 entered bar() method
Thread 1 entered foo() method
Thread 2 is trying to call ashok.last()
Thread 1 is trying to call vinod.last()
...
...
...
// Here cursor always waiting.
Dead lock


Scroll to top