Sunday 20 June 2021

Deadlocks in JAVA

A special type of error that you need to avoid that relates specifically to multitasking is

deadlock, which occurs when two threads have a circular dependency on a pair of synchronized

objects. For example, suppose one thread enters the monitor on object X and another thread

enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y,

it will block as expected. However, if the thread in Y, in turn, tries to call any synchronized

method on X, the thread waits forever, because to access X, it would have to release its own

lock on Y so that the first thread could complete. Deadlock is a difficult error to debug for

two reasons:

• In general, it occurs only rarely, when the two threads time-slice in just the right way.

• It may involve more than two threads and two synchronized objects

//Deadlocks in java

 class DeadLockDemo

{

public static void main(String args[])

{

String r1="Resource 1";

String r2="Resource 2";

Thread t1=new Thread()

{

public void run()

{

synchronized(r1)

{

System.out.println("Locked R1");

try

{

Thread.sleep(300);

}

catch(Exception e){}

synchronized(r2)

{

System.out.println("Locked R2");

}

}

}

};

Thread t2=new Thread()

{

public void run()

{

synchronized(r2)

{

System.out.println("Locked R2");

try

{

Thread.sleep(300);

}

catch(Exception e){}

synchronized(r1)

{

System.out.println("Locked R1");

}

}

}

};

t1.start();

t2.start();

}

}

No comments:

Post a Comment