Sunday, 2 March 2014

java Dead lock Example



Dead lock is a situation where two or more threads block forever. In Operating system dead lock occurs, when one process or thread is waiting for a resource, where this resource is in use by other process, which in turn waiting for other resource.

Dead lock is a common problem in multi threading environment. Care must be taken while developing multi threading Applications.

As you see the above figure,
process p1, acquires the resource R1, and waiting for the resource R2
process p2 acquires the resource R2, and waiting for the resource R1.

P1 releases the resource R1, once it finishes its task, but to finish its task, p1 needs rsource R1, which is in use by p2, so process p1 waits infinitely. Same thing happen with p2 also. So it is a deadlock, where processes p1 and p2 waiting infinitely.

Will implement the same model to create a dead lock using java.

interface Resource{
 void startExec(Resource r)throws Exception;
 public void end();
}

class Resource1 implements Resource{
 synchronized public void startExec(Resource r2)throws Exception{
  Thread.currentThread().sleep(2000);
  System.out.println(Thread.currentThread().getName() + " started \nAbout to call the end method of resource r2");
  r2.end();
 }

 synchronized public void end(){
  System.out.println("End");
 }
}
  

class Resource2 implements Resource{
 synchronized public void startExec(Resource r1)throws Exception{
  Thread.currentThread().sleep(2000);
  System.out.println(Thread.currentThread().getName() + " started \nAbout to call the end method of resource r1");
  r1.end();
 }

 synchronized public void end(){
  System.out.println("End");
 }
}

class DeadLockEx implements Runnable{
 Resource r1, r2;

 public void run(){
  try{
   r1.startExec(r2);
  }
  catch(Exception e){
  }
 }

 DeadLockEx(Resource r1, Resource r2){
  this.r1 = r1;
  this.r2 = r2;
 }

 public static void main(String args[]){
  Resource1 r1 = new Resource1();
  Resource2 r2 = new Resource2();

  DeadLockEx obj1 = new DeadLockEx(r1, r2);
  DeadLockEx obj2 = new DeadLockEx(r2, r1);

  Thread task1 = new Thread(obj1);
  Thread task2 = new Thread(obj2);

  task1.setName("p1");
  task2.setName("p2");

  task1.start();
  task2.start();
 }
}

Output   
p1 started
About to call the end method of resource r2
p2 started
About to call the end method of resource r1

task1 calls the synchronized method startExec() of resource r1, so r1 is locked.
task2 calls the synchronized method startExec() of resource r2, so r2 is locked.

Task1 tries to call the synchronized method end() of resource r2, but r2 is locked, so it waits for the resource.

Task2 tries to call the synchronized method end() of resource r1, but r1 is locked, so it waits for the resource.

Task1 and task2 waits infinitely. So Deadlock happened.



Dead lock                                                 Print Current stack trace                                                 Home

No comments:

Post a Comment