×

How to avoid deadlock in java

Deadlock:

A deadlock is an event that never going to occur. In java, deadlock is just a part of the multithreading. It is an environment that allows us to run multiple threads sequentially for multitasking. In some cases, the different threads themselves will be waiting and it lasts for a forever state which is called deadlock.

In the thread, every block has a lock. To make a lock, it provides synchronization to lock to a method or block of code.

How to avoid deadlock in java

How to avoid deadlock in java:

  • Avoid Unnecessary Locks: We should assign the locks for only those blocks on which it is going to perform the operations. The unnecessarily using of locks will leads to a deadlock condition. We suggest that you use a lock-free data structure. otherwise, keep your code free from locks. For example, use the concurrent linked queue instead of using a synchronized array list.
  • Avoid Nested Locks: The other possible way to avoid deadlock is to avoid assigning a lock to multiple threads at a time if we have already assigned a lock to one thread then we must avoid assigning a lock to multiple threads otherwise it leads to a deadlock.
  • Using Thread.join() Method: we get a deadlock if we use two threads or more threads waiting for each other to complete by using another thread to join method. If our thread has to wait for another thread to complete, then it's always the best way to use the join method with the maximum time you want to wait for the other thread to finish.
  • Use Lock Ordering: We should assign a numeric value to each lock when we are performing the operation. Before assigning the lock with a high numeric value, then we should acquire the locks with the least numeric value.
  • Lock Time-out: We can also specify the time for a thread to perform a lock. If a thread does not assign a lock, then that thread must wait for a particular time before retrying to acquire a lock.

Example:

public class DeadlockTest {
   public static void main(String[] args) throws InterruptedException {
      Demo obj1 = new       Demo ();
            Demo obj2 = new       Demo ();
           Demo obj3 = new       Demo ();
      Thread t1 = new Thread(new SyncThread(obj1, obj2), "t1");
      Thread t2 = new Thread(new SyncThread(obj2, obj3), "t2");
      t1.start();
      Thread.sleep(2000);
      t2.start();
      Thread.sleep(2000);
   }
}
class SyncThread implements Runnable {
   private       Demo obj1;
   private      Demo obj2;
   public SyncThread(      Demo o1,       Demo o2){
      this.obj1=o1;
      this.obj2=o2;
   }
   @Override
   public void run() {
      String name = Thread.currentThread().getName();
      System.out.println(name + " allocating lock on " + obj1);
      synchronized (obj1) {
         System.out.println(name + " allocated lock on " + obj1);
         work();
      }
      System.out.println(name + " removed lock on " + obj1);
      System.out.println(name + " allocating lock on " + obj2);
      synchronized (obj2) {
         System.out.println(name + " allocating lock on " + obj2);
         work();
      }
      System.out.println(name + " removed lock on " + obj2);
      System.out.println(name + " completed execution.");
   }
   private void work() {
      try {
         Thread.sleep(5000);
      } catch (InterruptedException ie) {
         ie.printStackTrace();
      }
   }
}

Output:

t1 allocated g a lock on java. lang.Demo@917d8d4
t1 allocated lock on java. lang. Demo@ 917d8d4
t2 allocating lock on java. lang. Demo@ 5c4b42fb
t2 allocated lock on java. lang. Demo@ 5c4b42fb
t1 released the lock on java. lang. Demo@917d8d4
t1 allocating a lock on java. lang. Demo@ 5c4b42fb
t1 allocated lock on java. lang. Demo@ 5c4b42fb
t2 released the lock on java. lang.Object@5c4b42fb
t2 allocating lock on java. lang. Demo@ 528cb702
t2 allocated lock on java. lang. Demo@ 528cb702
t1 removed the lock on java. lang. Demo@ 5c4b42fb
t2 removed the lock on java. lang. Demo@ 528cb702
t1 completed execution.
t2 completed execution.

Deadlock occurs

Example:

// Importing the required packages
import java.io.*;
import java.util.*;
 
// Class 1
class Demo {
 
    public synchronized void last()
    {
 
        // Print and display the statement
        System. out.println("Inside Demo, last() method");
    }
    
    public synchronized void d1(B b)
    {
        System.out.println(
            "Thread1 start execution of d1() method");
        try {
 
            // Putting the existing thread to sleep for
            // specific time using sleep() method
            Thread.sleep(2000);
        }
 
        // Catch block to handle the exceptions
        catch (InterruptedException e) 
            System.out.println(e);
        }
 
        System.out.println(
            "Thread trying to call B's last() method");
 
        // Calling method 1 of this class as created
        // above
        b.last();
    }
}
 
// Class 2
// Helper class Sample
class Sample {
 
    // Method 1 of this class
    public synchronized void last()
    {
 
        // Display statement only
        System.out.println("Inside Sample, last() method");
    }
    public synchronized void d2(Demo a)
    {
 
        // Display message only
        System.out.println(
            "Thread2 start execution of d2() method");
 
        try {
            Thread.sleep(2000);
         }
        catch (InterruptedException e) {
             System.out.println(e);
        }


        System.out.println(
            "Thread2  trying to call A's last method");
        a.last();
    }
}
 
// Deadlock class which is extending Thread class
class Simple extends Thread {
 
    // Creating object of type class Demo
    Demo a = new Demo();
 
    // Creating object of type class Sample
    Sample b = new Sample();
 
    public void m1()
    {
 
        // Starting the thread
        this.start();
 
        // Calling d1 method of class A
        a.d1(b);
    }
 
    // run() method for the thread
    public void run()
    {
 
        // Calling d2 method of class B
        b.d2(a);
    }
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating object of this class
        Simple deadlock = new Simple();
 
        // Calling the m1 method
        deadlock.m1();
    }
}

Related Topics

Access Modifier in Java

The access modifiers in java are used to change the accessibility and scope of a method, constructor, class, and fields. If you are aware of C++ language, when we declare any member...

2 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Java Math subtractExact() Method

The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long. Syntax: public static int subtractExact (int x,...

1 minute read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

How to Concatenate Two Strings in Java

How to Concatenate Two Strings in Java Concatenation of two strings means adding the beginning of one string to the end of the other string. Some of the ways to concatenate...

3 minutes read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.