Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
deadlock
os
concurrency
communitycreator

How do you handle deadlock in Java?

Anjana Shankar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring