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.

 

Output

 


 

0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Don Sannella
9 years ago

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 http://www.contemplateltd.com/threadsafe 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.)

Previous article

Send an email through Gmail in Java

Next article

Tracking thread pool in Java