Deadlock condition



Deadlock is a programming situation where two or more threads are blocked forever, this situation arises with at least two threads and two or more resources.

Here is a perfect implementation of Deadlock situation.
public static void main(String[] args)
{
 //Limited equipment need to share by 2 nurse.
 Equipment scissor = new Equipment("scissor");
 Equipment bandage = new Equipment("bandage");
 Equipment anticeptic = new Equipment("anticeptic");

 //Maria want to use scissor, bandage and antiseptic
 Equipment e1[] = new Equipment[]{scissor,bandage,anticeptic};
 Nurse nurse1 = new Nurse("Maria",e1);

 //Tina want to use bandage,antiseptic and scissor
 Equipment e2[] = new Equipment[]{bandage,anticeptic,scissor};
 Nurse nurse2 = new Nurse("Tina",e2);

 //Both are different thread..
 nurse1.start();
 nurse2.start();
}
Nurse.java
class Nurse extends Thread{
 String name=null;
 Equipment equipment[];
 Nurse(String n,Equipment[]e){
  this.name = n;
  this.equipment = e;
 }
 boolean stillAlive(long startTime){
  long waitTime = (System.currentTimeMillis() - startTime)/1000;
  if(waitTime > 30){
   System.out.println(this.name + "'s patient certified died after "+ waitTime + " sec");
   return false;
  }else{
   return true;
  }
 }
 public void run(){
  long startTime = System.currentTimeMillis();
  int i=0;
  while(i < equipment.length){
   //check patient to see still alive or not.
   if(!stillAlive(startTime)){
    //certified dead.
    break;
   }
   //trying to get equipment
   if(equipment[i].lock(this.name)){
    System.out.println(this.name + " got " + equipment[i].name);
    i++;
    if(i==equipment.length){
     System.out.println(this.name + " saved the patient");
    }
   }else{
    System.out.println(this.name + " waiting " + equipment[i].name + "(" + equipment[i].owner + " is holding)");
   }
   try {
    //simulate wait for other nurse to release
    long sleepPeriod = Math.abs(new Random().nextLong()%10000);
    Thread.sleep(sleepPeriod);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }

  //finish use.. release lock
  for(int j=0;j < equipment.length; j++){
   equipment[j].release();
  }
 }
}
Equipment.java
class Equipment{
 String name=null;
 String owner=null;

 Equipment(String n){
  this.name = n;
 }
 synchronized boolean lock(String o){
  if(owner==null){
   this.owner = o;
   return true;
  }
  return false;
 }
 synchronized void release(){
  this.owner = null;
 }
}

Comments