How to Avoid Deadlock in Java Threads
Want to learn how you can avoid deadlocks in Java? Check out this post to learn more about the conditions for creating a deadlock in Java threads.
Join the DZone community and get the full member experience.
Join For FreeWant to learn how to avoid deadlock in Java? The question of avoiding deadlock is one of the popular Java interview questions, with multi-threading being asked mostly at a senior level interview with lots of follow up questions. Even though the question looks very basic, most of the Java developers get stuck once you start going deeper.
So, what is a deadlock? The answer is simple — when two or more threads are waiting for each other to release the resource they need (lock) and get stuck for infinite time, the situation is called deadlock. It will only happen in the case of multitasking or multi-threading.
How Do you Detect Deadlock in Java?
Though this could have many answers, first, I would look at the code to see if a nested synchronized block is calling a synchronized method from another or if it is trying to get a lock on a different object. If that is the case, there is a good chance of deadlock, if the developer is not careful.
Another way to determine deadlock risks is when you actually get dead-locked while running the application. If this happens, try to take a thread dump, in Linux you can do this by the command "kill -3." This will print the status of all threads in an application log file, and you can see which thread is locked on which object.
You can analyze that thread dump with using tools like fastthread.io, which allows you to upload your thread dump and analyze it.
Another way is to use the jConsole/VisualVM. It will show you exactly which threads are getting locked and on which object.
If you are interested in learning about troubleshooting tools and the process to analyzing your thread dump, I suggest you take a look at this Analyzing Java Thread Dumps course on Pluralsight by Uriah Levy. This is an advanced practice course to learn more about Java thread dump and familiarize you with other popular advanced troubleshooting tools.
Write a Java Program That Will Result in Deadlock
Once you answer the earlier question, they may ask you how to write code that will result in a deadlock in Java.
Here is one way of doing it:
/**
* Java program to create a deadlock by imposing circular wait.
*
* @author WINDOWS 8
*
*/
public class DeadLockDemo {
/*
* This method request two locks, first String and then Integer
*/
public void method1() {
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
}
}
}
/*
* This method also requests same two lock but in exactly
* Opposite order i.e. first Integer and then String.
* This creates potential deadlock, if one thread holds String lock
* and other holds Integer lock and they wait for each other, forever.
*/
public void method2() {
synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
}
If method1()
and method2()
are both called by two or more threads, there is a good chance of deadlock, because if Thread 1 acquires a lock on a String object while executing method1()
and Thread 2 acquires a lock on the Integer object while executing method2()
, both will be waiting for each other to release a lock on the Integer and String to proceed further, which will never work.
This diagram effectively demonstrates our program, where one thread holds a lock on one object and is waiting for the other object to lock, which is held by the other thread.
You can see that Thread 1 wants the lock on Object 2, which is held by Thread 2, and Thread 2 wants a lock on Object 1, which is held by Thread 1. Since no thread is willing to give up, there is a deadlock and the Java program is stuck.
The idea is that you should know the right way to use common concurrent patterns, and if you are not familiar with them then Applying Concurrency and Multi-threading to Common Java Patterns by Jose Paumard is a good starting point to learn.
How to Avoid Deadlock in Java
Now, the interviewer comes to the final part and one of the most important questions, in my opinion: How do you fix a deadlock in code?
If you have looked at the above code carefully, then you may have figured out that the real reason for deadlock is not multiple threads, but it is the way that they are requesting a lock. If you provide an ordered access, then the problem will be resolved.
Here is my fixed version, which avoids deadlock by using a circular wait with no preemption. This is one of the four conditions needed for deadlock.
public class DeadLockFixed {
/**
* Both method are now requesting lock in same order, first Integer and then String.
* You could have also done reverse e.g. first String and then Integer,
* both will solve the problem, as long as both method are requesting lock
* in consistent order.
*/
public void method1() {
synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
public void method2() {
synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
}
Now, there would not be any deadlock, because both methods are accessing a lock on the Integer and String class literal in the same order. So, if Thread A acquires a lock on the Integer object, Thread B will not proceed until Thread A releases the Integer lock. This is done in the same way Thread A will not be blocked, even if Thread B holds a String lock, because, now, Thread B will not expect Thread A to release an Integer lock to proceed any further.
Further Learning
Multithreading and Parallel Computing in Java
Java Concurrency in Practice - The Book
Applying Concurrency and Multi-threading to Common Java Patterns
Java Concurrency in Practice Bundle by Heinz Kabutz
10 Java Multithreading and Concurrency Best Practices
Top 50 Multithreading and Concurrency Questions in Java
Read more: https://javarevisited.blogspot.com/2018/08/how-to-avoid-deadlock-in-java-threads.html#ixzz5Nh8XUhXP
Published at DZone with permission of Javin Paul, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments