a concise shot of dev knowledge
Become a Contributor
Concise shots of dev knowledge

RELATED TAGS

java
deadlock
os
concurrency
communitycreator

How do you handle deadlock in Java?

Anjana Shankar

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
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.

soc2