Deadlock in Java: What It Is and How to Avoid It
A deadlock in Java is a situation in a multithreaded program where two or more threads wait for each other forever: each one holds a resource the other needs, so none of them can continue. In Java, a deadlock usually happens when threads acquire synchronized monitors in different orders and end up in a circular dependency.
You won't get an exception. Nothing is printed to the console, the CPU is idle, and the program simply stops responding and never exits. The JVM does not resolve a deadlock on its own — the only way to see it is a thread dump.
Picture two kids in kindergarten, Alice and Bob, making a paper collage. Each of them needs scissors and colored paper. Alice grabs the scissors (the Alice thread enters the monitor of the scissors object), and Bob grabs the paper (the Bob thread enters the monitor of the paper object). Each waits for the other item and refuses to give up the one they already have. Neither can go on, and they'll wait forever (or until the teacher steps in).
Java Deadlock Example
All you need for a deadlock in Java is two threads and two monitor objects: the first thread locks them in the order A → B, the second in the order B → A. Once each thread holds its first monitor, neither will ever get the second one. Here is the Alice and Bob story in code.
import java.util.concurrent.CountDownLatch;
public class DeadlockExample {
private static final Object scissors = new Object();
private static final Object paper = new Object();
// Latch with a count of 2: each kid reaches for the second item
// only after both have taken their first one
private static final CountDownLatch bothTookFirst = new CountDownLatch(2);
public static void main(String[] args) {
Thread alice = new Thread(DeadlockExample::doSun, "Alice");
Thread bob = new Thread(DeadlockExample::doCloud, "Bob");
alice.start();
bob.start();
}
static void doSun() {
synchronized (scissors) {
System.out.println(name() + " took the scissors to cut out a sun");
waitForOther();
synchronized (paper) { // Alice gets stuck here
System.out.println(name() + " took the paper and is cutting out a sun");
}
}
}
static void doCloud() {
synchronized (paper) {
System.out.println(name() + " took the paper to cut out a cloud");
waitForOther();
synchronized (scissors) { // Bob gets stuck here
System.out.println(name() + " took the scissors and is cutting out a cloud");
}
}
}
private static void waitForOther() {
bothTookFirst.countDown();
try {
bothTookFirst.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private static String name() {
return Thread.currentThread().getName();
}
} Alice took the scissors to cut out a sun
Bob took the paper to cut out a cloud The order of these two lines may change from run to run, but a third line never appears: the program hangs and does not exit. Both threads are in the BLOCKED state, which is the state of a thread waiting to enter a synchronized block whose monitor is held by another thread. Alice is waiting for the paper monitor held by Bob, and Bob is waiting for the scissors monitor held by Alice. A monitor is released only when its owner leaves the synchronized block, and here neither owner ever does.
CountDownLatch from java.util.concurrent is used here only to make the deadlock reproducible on every run: countDown() decrements the counter, and await() blocks until it reaches zero. Without the latch, one thread could grab both items before the other even starts.
Why a deadlock often shows up only sometimes
A more typical version of this bug looks harmless: both threads run the same code, first doSun() (scissors → paper), then doCloud() (paper → scissors), with no latch. A deadlock is still possible, but only with unlucky timing: one thread has already finished doSun() and entered doCloud(), taking the paper, while the other is inside doSun() holding the scissors. Most of the time the threads just take turns and the program exits normally.
That's exactly how deadlocks behave in real projects. Tests pass, everything works on your machine, and then one day the service freezes under load. Ten runs without a hang prove nothing — the danger is the inconsistent lock order itself, not how often it fires.
4 Conditions for a Deadlock (Coffman Conditions)
A deadlock can occur only when four conditions hold at the same time, as described by Edward Coffman in 1971: mutual exclusion, hold and wait, no preemption, and circular wait. Break any one of them and a deadlock becomes impossible.
| Condition | What it means in Java | How to break it |
|---|---|---|
| Mutual exclusion | Only one thread can hold an object's monitor | Don't share the resource: immutable objects, per-thread copies of data |
| Hold and wait | A thread holds one monitor and waits for another | Acquire all required resources at once, or release what you hold if you can't get the next one (tryLock) |
| No preemption | A monitor can't be taken away from a thread — it is released only when the thread leaves synchronized | Locks with a timeout or interruption: tryLock(timeout), lockInterruptibly() |
| Circular wait | Alice waits for Bob, Bob waits for Alice (or A → B → C → A) | The same lock order in every thread — the simplest and most reliable fix |
How to Avoid Deadlock in Java
The main way to avoid deadlock in Java is to acquire locks in the same order in every thread: then a circular wait can't form. tryLock() with a timeout and keeping synchronized blocks small help as well.
Use a consistent lock order
Let's agree that the scissors are always taken first. A kid who didn't get the scissors waits while holding nothing, so no cycle can form:
public class DeadlockFixedExample {
private static final Object scissors = new Object();
private static final Object paper = new Object();
public static void main(String[] args) {
new Thread(DeadlockFixedExample::doSun, "Alice").start();
new Thread(DeadlockFixedExample::doCloud, "Bob").start();
}
static void doSun() {
synchronized (scissors) { // 1. scissors
synchronized (paper) { // 2. paper
System.out.println(name() + " is cutting out a sun");
}
}
}
static void doCloud() {
synchronized (scissors) { // same order: scissors,
synchronized (paper) { // then paper
System.out.println(name() + " is cutting out a cloud");
}
}
}
private static String name() {
return Thread.currentThread().getName();
}
} Alice is cutting out a sun
Bob is cutting out a cloud The lines may swap places, but the program always exits.
Easy to get wrong
If you copy waitForOther() with the CountDownLatch from the first example into the fixed version, the program hangs again. Alice takes the scissors and waits on await(), while Bob can never call countDown() because he is stuck in front of the scissors she holds. Waiting inside synchronized is part of the cycle too, even when it isn't a monitor. The same goes for Thread.sleep() and join(): neither releases the monitor. Only wait() gives up the monitor while the thread is waiting.
Lock order for objects passed as parameters
A consistent order is easy when the monitors are two well-known fields. It gets harder when the objects come in as method arguments. The classic case is a money transfer between accounts:
public void transfer(Account from, Account to, int amount) {
synchronized (from) {
synchronized (to) {
from.withdraw(amount);
to.deposit(amount);
}
}
} The code looks tidy: always "from first, then to". But if one thread calls transfer(a, b, 100) and another calls transfer(b, a, 50), the actual order differs, and you get the same Alice-and-Bob deadlock. The fix is to order the objects by a stable key, such as the account's unique id:
public void transfer(Account from, Account to, int amount) {
Account first = from.getId() < to.getId() ? from : to;
Account second = from.getId() < to.getId() ? to : from;
synchronized (first) {
synchronized (second) {
from.withdraw(amount);
to.deposit(amount);
}
}
} tryLock() with a timeout
You can't "try" to acquire a synchronized monitor: a thread either gets it or waits indefinitely. The Lock interface from java.util.concurrent.locks (implemented by ReentrantLock) can wait for a limited time and report failure:
Lock scissors = new ReentrantLock();
Lock paper = new ReentrantLock();
boolean done = false;
if (scissors.tryLock(100, TimeUnit.MILLISECONDS)) { // throws InterruptedException
try {
if (paper.tryLock(100, TimeUnit.MILLISECONDS)) {
try {
cutSun();
done = true;
} finally {
paper.unlock();
}
}
} finally {
scissors.unlock();
}
}
// if done == false, we hold nothing and can wait and retry If the thread can't get the paper within 100 ms, it releases the scissors, which breaks the "hold and wait" condition. Retry after a random pause: if two threads back off and retry in lockstep, you get a livelock (see below).
Keep the locked region small
The less code inside synchronized, the lower the chance that it acquires another monitor. Calling "foreign" code while holding a lock is especially risky: listeners, callbacks, methods of other objects that are synchronized themselves. You have no control over which monitors they take or in what order. Copy the data you need under the lock, leave the synchronized block, and only then call the external code.
How to Detect a Deadlock: jstack, VisualVM, ThreadMXBean
To detect a deadlock in a running Java program, take a thread dump with the JDK's jstack (or jcmd) tool: the JVM finds cycles on monitors itself and prints "Found one Java-level deadlock" at the end of the dump, along with the names of the threads and the objects they are waiting for.
First find the process ID, then take the dump:
jps -l # list Java processes and their PIDs
jstack 12345 # thread dump of process 12345
jcmd 12345 Thread.print # the same via jcmd For the hung DeadlockExample, the end of the dump looks roughly like this (your addresses will differ):
Found one Java-level deadlock:
=============================
"Alice":
waiting to lock monitor 0x000001f3a8c0e2d0 (object 0x0000000711c09f48, a java.lang.Object),
which is held by "Bob"
"Bob":
waiting to lock monitor 0x000001f3a8c0d8f0 (object 0x0000000711c09f38, a java.lang.Object),
which is held by "Alice"
...
Found 1 deadlock. This is where the thread names pay off: "Alice" and "Bob" are much easier to read in a dump than Thread-0 and Thread-1. Give your threads meaningful names in production code.
Graphical tools do the same job. JConsole (ships with the JDK, run jconsole) has a "Detect Deadlock" button on the Threads tab. VisualVM is no longer bundled with the JDK since JDK 9 and has to be downloaded separately; on its Threads tab it highlights a detected deadlock and lets you take a thread dump.
You can also detect a deadlock from inside the program with ThreadMXBean. For example, add this to the end of main() in the first example (and declare throws InterruptedException):
// import java.lang.management.*;
Thread.sleep(500); // give the threads time to block
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long[] ids = bean.findDeadlockedThreads(); // null if there is no deadlock
if (ids != null) {
for (ThreadInfo info : bean.getThreadInfo(ids)) {
System.out.println(info.getThreadName() + " is waiting for " + info.getLockName()
+ ", held by " + info.getLockOwnerName());
}
} Alice is waiting for java.lang.Object@1b6d3586, held by Bob
Bob is waiting for java.lang.Object@4554617c, held by Alice Your hash codes and line order will differ. The program still won't exit afterwards: the deadlock is detected, not fixed. findDeadlockedThreads() finds cycles on both synchronized monitors and ReentrantLock; the older findMonitorDeadlockedThreads() sees monitors only.
Deadlock vs Livelock vs Starvation
In a deadlock, threads are blocked and do nothing; in a livelock, threads keep running but endlessly yield to each other and make no progress; in starvation, one thread can't get a resource for a long time while the others work normally.
A livelock is like two people in a narrow corridor who both step to the same side to let the other pass, then both step to the other side, and so on forever. In code it's usually a loop of "try tryLock(), fail, release, retry immediately" in two threads running at the same rhythm.
| Aspect | Deadlock | Livelock | Starvation |
|---|---|---|---|
| Thread state | BLOCKED or WAITING | RUNNABLE, actively working | The "starving" thread waits for long periods, the rest work |
| CPU usage | Near zero | High | Normal |
| Progress | None for any thread in the cycle | None for any thread in the group | Everyone except the "starving" thread |
| Visible in jstack | Yes, "Found one Java-level deadlock" | No — threads look busy | No |
| How to fix | Consistent lock order, tryLock | Random pause before retrying | Don't hold a monitor for long; fair lock new ReentrantLock(true); don't rely on thread priorities |
Deadlocks in a Database
A database deadlock is the same circular wait, but between transactions: each one has locked rows the other needs. The key difference from a Java deadlock is that the database detects the cycle itself and rolls back one of the transactions, while the JVM leaves the threads hanging forever.
A typical scenario: transaction 1 updates row A, then B; transaction 2 updates B first, then A. After a short while the database notices the cycle and picks a "victim". In PostgreSQL this is ERROR: deadlock detected (SQLSTATE 40P01); in MySQL InnoDB it's ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction. The Java application receives an SQLException with that SQLState and has to retry the whole transaction. Prevention works the same way as in Java code: update rows in the same order in every transaction and keep transactions short.
Frequently Asked Questions
Can a program recover from a deadlock without a restart?
Not if the threads are blocked on synchronized. A thread in the BLOCKED state ignores interrupt(): the interrupt flag is set, but the thread keeps waiting for the monitor. The only way out is restarting the JVM. Recovery is possible only with ReentrantLock acquired via tryLock(timeout) or lockInterruptibly(). That's why deadlocks need to be prevented rather than cured — see How to Avoid Deadlock in Java.
Can a thread deadlock itself?
Not on a single monitor: synchronized is reentrant, so a thread that already owns a monitor enters it again without waiting. But a thread can wait for itself forever in another way: Thread.currentThread().join() never returns, because the thread is waiting for its own termination. This isn't considered a classic deadlock — there is no cycle between different threads.
How many threads does a deadlock need?
At least two, but the cycle can be longer: thread A waits for B, B waits for C, C waits for A. The well-known model of this is the dining philosophers problem: five philosophers with one fork between each pair, and if everyone picks up the left fork at the same time, they all wait forever for the right one. The fix is the same consistent lock order: number the forks and have everyone pick up the lower-numbered fork first.
What's the difference between a deadlock and a race condition?
A race condition means too little synchronization: threads modify shared data at the same time and the result is wrong. A deadlock means synchronization is wrong or excessive: the data stays intact, but the program stops. When you fix a race condition with synchronized, watch the order in which monitors are acquired so you don't trade one bug for a deadlock.
Comments