Trusted answers to developer questions

How do you handle deadlock in Java?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Overview

Deadlock is a condition where two or more threads are waiting for a resource that is held by another thread, effectively staying in the wait loop forever.

Example: Deadlock

Let's see an example of a Java program that is in deadlock.

Note: If the program seems stuck, it is in deadlock. Wait for the execution time to complete.

public class Deadlock{
public static void main(String[] args){
final String s1 = "anjana";
final String s2 = "shankar";
Thread t1 = new Thread() {
public void run(){
synchronized(s1){
System.out.println("Thread 1: Locked s1");
try{ Thread.sleep(100);} catch(Exception e) {}
synchronized(s2){
System.out.println("Thread 1: Locked s2");
}
}
}
};
Thread t2 = new Thread() {
public void run(){
synchronized(s2){
System.out.println("Thread 2: Locked s2");
try{ Thread.sleep(100);} catch(Exception e) {}
synchronized(s1){
System.out.println("Thread 2: Locked s1");
}
}
}
};
t1.start();
t2.start();
}
}

Avoiding deadlock

The following are some recommendations in order to avoid deadlocks, although it is not possible to guarantee deadlock avoidance.

  1. Nested locks: Avoid giving locks to multiple threads.
  2. Unnecessary locks: Locks should only be given to important threads.
  3. Thread join: Use Thread.join() with a maximum wait time that a thread can take.

RELATED TAGS

java
deadlock
os
concurrency
Did you find this helpful?