How to Create a Deadlock in Java

If you are asked what is deadlock in Java it is almost always accompanied by the question how to create a deadlock in Java.

Deadlock in multi-threading is a scenario where two or more threads are waiting for each other to release the resources to make any further progress and blocked forever in the process.

Java program for creating deadlock

You may get deadlock in Java when you have nested synchronized blocks with reverse ordering of objects.

In the example two threads are created to run two separate runnable tasks. In each runnable task there are nested synchronized blocks acquiring object locks in reversed order thus creating a deadlock.

Output

You can see in run() method of ThreadA synchronized block acquires lock on obj1 and then tries to acquire lock on obj2. Same way in run() method of ThreadB synchronized block acquires lock on obj2 and then tries to acquire lock on obj1. This hangs the program by creating a deadlock as t1 thread is waiting to acquire lock on obj2 which is currently acquired by t2 thread and t2 thread is waiting to acquire lock on obj1 which is currently acquired by the t1 thread.

Creating deadlock by calling one synchronized method from another

Here is another example of creating deadlock in Java. It is similar to the first example here rather than having nested synchronized blocks there are two synchronized methods. The objects which are used to call the method and the object which are passed as an argument to these methods are reversed thus creating deadlock.

Output

From one thread synchronized method method1 is called using obj1 so this thread acquires a lock on obj1 then another synchronized method method2 is called using obj2.
From another thread synchronized method method1 is called using obj2 so this thread acquires a lock on obj2 then another synchronized method method2 is called using obj1.

That’s all for the topic How to Create a Deadlock in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.