DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Mastering Thread-Local Variables in Java: Explanation and Issues
  • Unlocking Performance: Exploring Java 21 Virtual Threads [Video]
  • Visualizing Thread-Safe Singletons in Java
  • Double-Checked Locking Design Pattern in Java

Trending

  • Apple and Anthropic Partner on AI-Powered Vibe-Coding Tool – Public Release TBD
  • Using Java Stream Gatherers To Improve Stateful Operations
  • Advancing Your Software Engineering Career in 2025
  • Chat With Your Knowledge Base: A Hands-On Java and LangChain4j Guide
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. How to Avoid Deadlock in Java Threads

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.

By 
Javin Paul user avatar
Javin Paul
·
Aug. 10, 18 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
76.9K Views

Join the DZone community and get the full member experience.

Join For Free

Want 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.

How do you avoid deadlock in Java?

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

Threading Java (programming language)

Published at DZone with permission of Javin Paul, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Thread-Local Variables in Java: Explanation and Issues
  • Unlocking Performance: Exploring Java 21 Virtual Threads [Video]
  • Visualizing Thread-Safe Singletons in Java
  • Double-Checked Locking Design Pattern in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!