Coders Packet

How to avoid Deadlock in Java.

By Vedanti Ravish Deshmukh

In Java, we work with multiple threads, and sometimes it leads to a deadlock situation. So, we have discussed the cause and solution below with an example.

What is a deadlock in Java and how it can be avoided?


Deadlock in Java- In a multithread program of Java, threads tend to lock themselves forever due to the usage of the synchronized keyword. This keyword tend to stop the execution of threads and block while waiting for the lock, associated with the specified object

How one should avoid this situation?
It is not possible to avoid the deadlock condition but we can avoid it by using the following ways:

1.Avoid Unnecessary Locks: We should use locks only for those members on which it is required.
2.Avoid Nested Locks: avoid allocating a lock to multiple threads
3.Using Thread.join() Method: If there are two threads waiting for each other to finish, use thread joins to avoid a deadlock situation.
4.Use Lock Ordering: Assign a numeric value to each lock.
5.Lock Time-out: Specify the time for a thread to acquire a lock.

Below is an example of how one should avoid deadlock:

public class Avoid_Deadlock
{
 public static void main(String[] args)
 {
   String string1 = "Vedanti";
   String string2 = "Deshmukh";
   Thread thread_1 = new Thread() 
   {
     public void run()
     {
       synchronized(string1)
       {
        System.out.println("Thread 1 has obtained Lock on string 1");
        try
        { 
            Thread.sleep(472);
        } 
        catch(Exception e){
        }
      synchronized(string2){
        System.out.println("Thread 1 has obtained Lock on String 2");
        }
     }
  }
};
 Thread thread_2 = new Thread() 
 {
      public void run()
      {
       synchronized(string1)
       {
        System.out.println("Thread 2 has obtained Lock on string 1");
        
        try
        { 
            Thread.sleep(472);
        } 
        catch(Exception e){
        }
      synchronized(string2)
      {
       System.out.println("Thread 2 has obtained Lock on string 2");
      }
    }
  }
};
thread_1.start();
thread_2.start();
}
}

 

The output of this program:

Thread 1 has obtained Lock on string 1
Thread 1 has obtained Lock on String 2
Thread 2 has obtained Lock on string 1
Thread 2 has obtained Lock on string 2

 

Download project

Reviews Report

Submitted by Vedanti Ravish Deshmukh (vedantid30)

Download packets of source code on Coders Packet