Deadlock


Deadlock

A programming scenario where two or more threads are blocked forever is called a deadlock in java. This situation comes up with at least two threads and two or more resources. When multiple threads need the same locks but obtain them in different orders leads to a deadlock situation. To detect a deadlock, we can use the java thread dump of the program. When the deadlock situation is analysed and the threads which are causing deadlock are found out, changes have to be made in the code to avoid deadlock situations.

Some ways to avoid deadlock:

  • Avoid nested locks
  • Avoid waiting indefinitely
  • Lock only what is required

The multithreaded program may experience the deadlock condition in java since the synchronized keyword creates the executing thread to block while waiting for the lock, or proctor, connected with the complex object.

How to Detect a DeadLock condition?

Programmers can detect Deadlock by running the program on the command prompt. It would be best if you got Thread Dump. Command to accumulate depends on OS type. If you are practicing on Windows and Java 8, the appropriate command is jcmd $PID Thread.print 
You can get PID by running the jps command.

Some points to remember

  • If two threads are waiting for one another to complete, then this condition is recognized as Deadlock.
  • The condition of Deadlock is a complex condition that occurs only in the state of multiple threads.
  • The condition of Deadlock can break the code at run time and can ruin business logic.
  • It is suggested to avoid this condition as much as possible.

Example:

Com.knowledge2life public class Main { public static void main(String[] args) { final String resource1 = "ratan jaiswal"; final String resource2 = "vimal jaiswal"; Thread t1 = new Thread() { public void run() { synchronized (resource1) { System.out.println("Thread 1: Knowledge2life locked resource"); try { Thread.sleep(100);} catch (Exception e) {} synchronized (resource2) { System.out.println("Thread 1: Knowledge2life locked resource"); } } } }; Thread t2 = new Thread() { public void run() { synchronized (resource2) { System.out.println("Thread 2: locked resource 2"); try { Thread.sleep(100);} catch (Exception e) {} synchronized (resource1) { System.out.println("Thread 2: locked resource 1"); } } } }; t1.start(); ō t2.start(); } }

OUTPUT:

Thread 1: locked resource 1
Thread 2: locked resource 2