Dead Lock

 Dead Lock: It is a phenomenon where multiple threads are stuck in Blocked state due to mutual dependency of the required resources. ( Lets say there are 2 threads A & B, so what ever resources required by A will be available at B and What ever the resources required by B will be available at A. Both of them have cyclic dependency and Both got stuck in blocked state.

Example:

class Warrior implements Runnable

{

String res1=new String("Brhmastra");

String res2=new String("PashuPatastra");

String res3=new String("Sarpastra");

public void run()

{

try

{

String s1=Thread.currentThread().getName();

if(s1.equals("Rama"))

{

ramaAcqRes();

}

else

{

ravanaAcqRes();

}

}

catch(Exception e )

{

System.out.println("Some interruption");

}

}

public void ramaAcqRes()

{

try

{

Thread.sleep(4000);

synchronized(res1)

{

System.out.println("Rama has acquired "+ res1);

Thread.sleep(4000);

synchronized(res2)

{

System.out.println("Rama has aquired "+ res2);

Thread.sleep(4000);

synchronized(res3)

{

System.out.println("Rama has aquired "+ res3);

}

}

}

}

catch(Exception e)

{

e.printStackTrace();

}

}

public void ravanaAcqRes()

{

try

{Thread.sleep(4000);

synchronized(res3)

{

System.out.println("Ravana has acquired "+ res3);

Thread.sleep(4000);

synchronized(res2)

{

System.out.println("Ravana has aquired "+ res2);

Thread.sleep(4000);

synchronized(res1)

{

System.out.println("Ravana has aquired "+ res1);

}

}

}

}

catch(Exception e)

{

e.printStackTrace();

}

}

}


public class LaunchDL {


public static void main(String[] args) {


Warrior w=new Warrior();

 

Thread t1=new Thread(w);

Thread t2=new Thread(w);

t1.setName("Rama");

t2.setName("Ravana");

t1.start();

t2.start();


}


}


Comments

Popular posts from this blog

Advantages and Disadvantages of Monolithic Architecture

Monolithic Architecture

Eclipse debugging