How to Solve Deadlock using Threads in Java? Last Updated : 15 Jun, 2022 Comments Improve Suggest changes Like Article Like Report If two threads are waiting for each other forever such type of infinite waiting is called deadlock in java. Synchronized keyword is the only reason for deadlock situation hence while using synchronized keyword we have to take special care. There is no resolution technique for deadlock, but several prevention techniques are available. Implementation: Deadlock occurs Example 1: Java // Java program to illustrate Deadlock // where deadlock occurs // Importing required packages import java.io.*; import java.util.*; // Class 1 // Helper class class A { // Method 1 of this class // Synchronized method public synchronized void last() { // Print and display statement System.out.println("Inside A, last() method"); } // Method 2 of this class // Synchronized method public synchronized void d1(B b) { System.out.println( "Thread1 start execution of d1() method"); // Try block to check for exceptions try { // Putting the current thread to sleep for // specific time using sleep() method Thread.sleep(2000); } // Catch block to handle the exceptions catch (InterruptedException e) { // Display the exception on the console System.out.println(e); } // Display statement System.out.println( "Thread trying to call B's last() method"); // Calling the method 1 of this class as created // above b.last(); } } // Class 2 // Helper class B class B { // Method 1 of this class public synchronized void last() { // Display statement only System.out.println("Inside B, last() method"); } // Method 2 of this class // Synchronized the method d2 public synchronized void d2(A a) { // Display message only System.out.println( "Thread2 start execution of d2() method"); // Try block to check for exceptions try { // Putting the current thread to sleep for // certain time using sleep() method Thread.sleep(2000); // Catch block to handle the exceptions } catch (InterruptedException e) { // Display the exception on the console System.out.println(e); } // Display message only System.out.println( "Thread2 trying to call A's last method"); // Again calling the last() method inside this class a.last(); } } // Class 3 // Main class // Deadlock class which is extending Thread class class GFG extends Thread { // Creating object of type class A A a = new A(); // Creating object of type class B B b = new B(); // Method 1 public void m1() { // Starting the thread this.start(); // Calling d1 method of class A a.d1(b); } // Method 2 // run() method for the thread public void run() { // Calling d2 method of class B b.d2(a); } // Method 3 // Main driver method public static void main(String[] args) { // Creating object of this class GFG deadlock = new GFG(); // Calling m1 method deadlock.m1(); } } Output: Output explanation: Here the cursor is showing forever because the threads enter into the deadlock situation. In the above program if we removed at least one synchronized keyword then the program won't enter into the deadlock situation. Hence, synchronized keyword is one of the major reason for deadlock situation. Due to this while using synchronized keyword we have to take special care. We can avoid Deadlock situation in the following ways: Using Thread.join() Method: We can get a deadlock if two threads are waiting for each other to finish indefinitely using thread join. Then our thread has to wait for another thread to finish, it is always best to use Thread.join() method with the maximum time you want to wait for the thread to finish.Use Lock Ordering: We have to always assign a numeric value to each lock and before acquiring the lock with a higher numeric value we have to acquire the locks with a lower numeric value.Avoiding unnecessary Locks: We should use locks only for those members on which it is required, unnecessary use of locks leads to a deadlock situation. And it is recommended to use a lock-free data structure and If it is possible to keep your code free from locks. For example, instead of using synchronized ArrayList use the ConcurrentLinkedQueue. Example 2: Deadlock is prevented Java // Java program to illustrate Deadlock // where deadlock is prevented from occurring // Importing required packages import java.io.*; import java.util.*; // Class 1 // Helper class class A { // Method 1 of this class // Synchronized method public synchronized void last() { // Print and display statement System.out.println("Inside A, last() method"); } // Method 2 of this class // Synchronized method public synchronized void d1(B b) { System.out.println( "Thread1 start execution of d1() method"); // Try block to check for exceptions try { // Putting the current thread to sleep for // specific time using sleep() method Thread.sleep(2000); } // Catch block to handle the exceptions catch (InterruptedException e) { // Display the exception on the console System.out.println(e); } // Display statement System.out.println( "Thread trying to call B's last() method"); // Calling the method 1 of this class as created // above b.last(); } } // Class 2 // Helper class B class B { // Method 1 of this class public void last() { // Display statement only System.out.println("Inside B, last() method"); } // Method 2 of this class // Non-synchronized the method d2 public void d2(A a) { // Display message only System.out.println( "Thread2 start execution of d2() method"); // Try block to check for exceptions try { // Putting the current thread to sleep for // certain time using sleep() method Thread.sleep(2000); // Catch block to handle the exceptions } catch (InterruptedException e) { // Display the exception on the console System.out.println(e); } // Display message only System.out.println( "Thread2 trying to call A's last method"); // Again calling the last() method inside this class a.last(); } } // Class 3 // Main class // Deadlock class which is extending Thread class class GFG extends Thread { // Creating object of type class A A a = new A(); // Creating object of type class B B b = new B(); // Method 1 public void m1() { // Starting the thread this.start(); // Calling d1 method of class A a.d1(b); } // Method 2 // run() method for the thread public void run() { // Calling d2 method of class B b.d2(a); } // Method 3 // Main driver method public static void main(String[] args) { // Creating object of this class GFG deadlock = new GFG(); // Calling m1 method deadlock.m1(); } } Output: Comment More infoAdvertise with us Next Article How to Solve Deadlock using Threads in Java? M mroshanmishra0072 Follow Improve Article Tags : Misc Java Java Programs Java-Multithreading Practice Tags : JavaMisc Similar Reads How to Copy a File in Multiple Threads Using Java? Copying files is a task, in programming that deals with file manipulation. Although Java offers tools, for file handling copying files can slow down our application's performance. To optimize this process, we can take advantage of multithreading, which enables threads to work on various sections of 3 min read How to Display all Threads Status in Java? Threads are light-weight processes within a process.. Multithreading in java is a feature that allows concurrent execution of two or more parts of a program to maximize the utilization of CPU. here the approach to retrieve the state of the thread is via getState() method of the Thread class. A java 2 min read How to Temporarily Stop a Thread in Java? The suspend() method of thread class puts the thread from running to waiting state. This method is employed if you would like to prevent the thread execution and begin it again when a particular event occurs. This method allows a thread to temporarily cease execution. The suspended thread is often r 2 min read How to make ArrayList Thread-Safe in Java? In Java, Thread is the smallest unit of execution within the program. It represents an independent path of execution that can run concurrently with other threads. When dealing with multi-threaded applications, where multiple threads are accessing and modifying data concurrently, it's crucial to ensu 3 min read How to Use Locks in Multi-Threaded Java Program? A lock may be a more flexible and complicated thread synchronization mechanism than the standard synchronized block. A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can ac 6 min read How to Monitor a Thread's Status in Java? The Java language support thread synchronization through the use of monitors. A monitor is associated with a specific data item and functions as a lock on that data. When a thread holds the monitor for some data item, other threads are locked out and cannot inspect or modify the data. In order to mo 3 min read How to Find Prime and Palindrome Numbers using Multi-Threading in Java? Multithreading in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to each other. Multiple threads don't 4 min read Producer Consumer Solution using BlockingQueue in Java Thread The Producer-Consumer problem is a synchronization issue that arises when one or more threads generate data, placing it on a buffer, and simultaneously, one or more threads consume data from the same buffer. Doing so can cause a race condition in which the threads are racing against each other to c 6 min read How to Get the Id of a Current Running Thread in Java? The getId() method of Thread class returns the identifier of the invoked thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused. Java allows c 4 min read Print even and odd numbers in increasing order using two threads in Java Given an integer N, the task is to write Java Program to print the first N natural numbers in increasing order using two threads.Prerequisite: MultithreadingExamples:Input: N = 10Output: 1 2 3 4 5 6 7 8 9 10Input: N = 18Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18Approach: The idea is to cre 3 min read Like