How to create a deadlock in Java

This article shows how to create a deadlock in Java.

A deadlock occurs when two threads each hold a lock that the other thread is waiting for. Neither of them can proceed without acquiring the lock held by the other thereby creating a deadlock.

To study and analyse a deadlock you should be able to create one. This article shows you how to do it.

First, we define two locks. Then, we create two threads that acquire both the locks one by one but in different orders. Thread A acquires lock A first then waits for sometime while Thread B acquires lock B. Then, thread A tries to acquire lock B and vice versa. And you have a deadlock created!

Let me show you the code.





Leave a Reply

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Don Sannella Recent comment authors
newest oldest
Notify of
Don Sannella

ThreadSafe is a static analysis tool that automatically finds Java concurrency defects. It finds this one, of course, but it also quickly finds much more complicated deadlocks and race conditions in million-line codebases. See for more information, and to get a free two-week trial.

(Disclosure: ThreadSafe is a commercial tool, and I’m co-founder of Contemplate, the company that produces it.)