Lesson · Multithreading Fundamentals
Deadlock: the four conditions and the one you control
16 min readDeadlock
Two threads, two locks, one interleaving: each thread holds what the other needs and neither will ever move again. Nothing crashes and nothing times out, so the incident arrives as a hang. Coffman's four conditions explain how it forms, thread dumps prove it happened, and lock ordering is the condition you actually control.
A hang, not a crash
Thread one holds lock A and waits for lock B. Thread two holds lock B and waits for lock A. Both waits are permanent, and neither thread will ever be told that it is waiting for something that will not come.
The JVM has no watchdog for this situation. The process stays alive, the heap stays put, main never returns, and the service simply stops answering. That is why a deadlock is diagnosed as a hang, and a hang starts with one question: is any thread still making progress?
A deadlock is a cycle; every fix removes an edge. If a fix does not delete one of the waits, it is a mitigation, not a repair.
The four conditions, and the one you control
Coffman described the four conditions in 1971, and all four must hold at the same time for a deadlock to form. Because each one is necessary, breaking any single one makes the cycle impossible.
Two of the four are what a lock is. The other two are what your code does with locks, which is where every practical fix lives.
- Mutual exclusion: a resource is held by one thread at a time. Standard locks cannot give this up; removing it means removing the lock itself.
- Hold and wait: a thread keeps one lock while requesting another. That is the state every transfer enters the moment it needs two accounts.
- No preemption: nothing can take a lock away from a thread. The JVM has no mechanism to break a cycle for you, unlike a database engine that rolls a victim transaction back.
- Circular wait: a closed chain where each thread waits for what the next one holds. This is the condition that code and convention can remove at no runtime cost.
Two conditions belong to the lock; two belong to your design. Mutual exclusion and no preemption come with the tool, so the fixes always reduce to hold and wait (bound the wait) or circular wait (order the locks).
Wait-for graph
Amber arrows are waits. The cycle is when they point at each other.The chip pairing is the whole diagnosis: T1 wants what T2 holds, and T2 wants what T1 holds. Ordering keeps four edges but makes the waits point one way.
The canonical case: transfer in opposite order
Two accounts, two transfers, opposite orders. transfer(A, B) locks A and then B; transfer(B, A) reaches the same method with the arguments swapped, so it locks B and then A. Both threads take their first lock, and then each requests a lock the other one owns.
The transactions lesson showed the database version of this picture: two transactions, two rows, and an engine that detects the cycle and rolls one victim back with SQLState 40P01 on PostgreSQL or error 1213 on MySQL. Nothing here does that for you. On the JVM the cycle simply stays.
// transfer(A, B) synchronized (A) { synchronized (B) { move(A, B); } } // transfer(B, A): the same method, arguments swapped synchronized (B) { synchronized (A) { move(B, A); } }
The same method with its arguments swapped became a cycle. A deadlock is a property of lock order, not of code quality.
Two threads · transfer(1, 2) vs transfer(2, 1)
transfer(A, B): wants A, then B
transfer(B, A): wants B, then A
Two accounts, A and B, and two transfers that want them in opposite orders: T1 runs transfer(A, B), T2 runs transfer(B, A). Both locks are free and both threads are ready.
Detection: three dumps before you believe one
A deadlocked process looks like a slow one from the outside, so the answer comes from a thread dump: jstack <pid>, or jcmd <pid> Thread.print, or the console signals that print the same information to stdout (Ctrl+Break on Windows, kill -3 on Unix).
HotSpot recognises monitor cycles and prints a section that begins with Found one Java-level deadlock. It names the threads, the monitors they wait on, and who holds them, so the cycle can be read straight off the output. Programmatically, ThreadMXBean.findDeadlockedThreads() (Java 6 and later) returns the same cycles for monitors and ownable synchronizers, which is how a health endpoint notices a deadlock without a human attaching.
- Take three dumps a few seconds apart, all by the same method, so the samples are comparable.
- Search each dump for Found one Java-level deadlock; a single dump can catch healthy threads mid-contention and look alarming.
- Confirm the same threads sit on the same waiting-for frames in all three samples; repetition is the proof, a snapshot is only a hint.
- Map the monitor addresses back to classes and lines, and read the owner chain: who holds what, and who is waiting for whom.
One dump is a snapshot; three are a diagnosis. A thread that spent a single sample waiting may be perfectly healthy. A cycle that shows up three times is not.
Fix one: a global lock order
Pick an immutable key on the objects you lock, account.id being the natural choice, and make every code path acquire locks in ascending key order. The second lock a thread requests is then either free or held by a thread that will finish, because no one waits for it while holding something the first thread needs.
The order is a rule, not a habit. Route every caller through one helper, and write the order down next to the class, because a single call site that locks out of order reinstates the cycle for everyone.
static void transfer(Account from, Account to, int amount) { Account first = from.id < to.id ? from : to; // a total order every caller shares Account second = from.id < to.id ? to : from; synchronized (first) { synchronized (second) { from.balance -= amount; to.balance += amount; } } }
Lock ordering is the rule you write down before the code, not after the incident. If two locks must nest, the order is part of the API contract.
The rest of the bench: tryLock, one lock, open calls
Ordering removes the cycle, but it needs every participant to agree on a key, and that is not always possible: locks on library objects, dynamic lock sets, locks chosen at runtime. The other techniques bound the wait instead, or remove the second lock entirely.
ReentrantLock.tryLock(timeout) is the main one. The thread gives up with false instead of waiting forever, releases what it holds, and retries later. Two cautions. The retry needs a jittered backoff or the threads re-collide on a schedule, which is the livelock lesson. And tryLock only helps where you called it: a lock() earlier in the same method restores the indefinite wait.
| Technique | What it removes | What it costs |
|---|---|---|
| Global ordering | Circular wait: the second request always points the same way | A shared immutable key and one funnel method; no runtime cost |
| tryLock with timeout | Hold and wait: the wait becomes bounded | A retry loop that needs jitter; without it the code livelocks instead |
| One lock per invariant | The second lock entirely | Coarser contention: operations that used to overlap now serialize |
| Open calls | Locks you did not know you were taking | Discipline: no callbacks, listeners or foreign code while a lock is held |
| Short critical sections | Time spent inside the cycle | Not a proof, but fewer windows and a faster recovery when one forms |
| Queue or message passing | Shared locks in that design | One owner thread and a bigger refactor; the state must have a single owner |
An open call is a lock you did not take. Calling foreign code under your lock hands a stranger the pen that draws edges into your wait-for graph.
The deadlock that is not a lock cycle
A fixed thread pool can deadlock with no monitor cycle anywhere. Task A submits task B to the same pool and waits on B's Future; every worker slot is now occupied by a task waiting for work that cannot start. The pool is full, the queue grows, and throughput is zero.
This one hides from the classics. A dump can show WAITING threads and no cycle, and ThreadMXBean.findDeadlockedThreads() can return null: the wait-for graph lives in your task graph, not in the monitors, so no tool reconstructs it for you.
- Never wait inside a pool task for another task in the same pool: the submission that could unblock you may sit in the queue behind the slot your own wait occupies.
- Separate pools or queues: one pool for tasks that wait on I/O or on results, another for CPU work, so a blocked task cannot consume the slots everything depends on.
- Structure dependent tasks: structured concurrency (StructuredTaskScope) keeps a parent and its children in one scope, so waiting happens in a construct that owns the task graph; the API went through several preview rounds, so check your JDK before depending on it.
- Virtual threads change the calculus: a virtual thread blocked on a Future unmounts from its carrier instead of holding a pool slot, which largely dissolves the fixed pool arithmetic. Monitor cycles are still deadlocks, and a blocked virtual thread inside synchronized code can pin its carrier (the virtual threads lesson has the details).
A lock deadlock shows up in a thread dump; a pool deadlock shows up in your task graph. When a fleet of workers is waiting and no cycle is reported, draw the second graph.
Reading a hang in five steps
Detection, classification, repair: in that order, every time. The sequence below is the playbook, and the repair is always the same idea seen from a different angle.
- Confirm there is no progress: logs stop, queues grow, throughput goes flat. That is a hang, not a slow path.
- Take three dumps and compare them; waits that repeat across all three rank first.
- If a dump names a Java-level deadlock, read the cycle and map the monitors back to classes and call sites.
- If it does not, check findDeadlockedThreads() for ownable synchronizers, then check your own wait graph: Futures, latches, pool submissions.
- Remove an edge: order the locks, bound the wait with tryLock, take a single lock, or hand the work to an owner thread. Then document the rule you chose.
Prevention beats detection: the dump tells you what already went wrong, ordering tells you where a cycle can never form.
The deadlock your tools cannot see
jstack and ThreadMXBean only find monitor and synchronizer cycles. A fixed pool whose tasks wait on each other's Futures is just as stuck, and every dump looks healthy: threads WAITING, no cycle, no message. When throughput is zero and no deadlock is reported, draw the wait-for graph of your own submissions.
Interview angles
What are the four Coffman conditions, and which one do you break in practice?+
Mutual exclusion, hold and wait, no preemption and circular wait; all four must hold, so breaking any one prevents the deadlock. In ordinary Java code you break circular wait with a global lock order, or hold and wait by replacing lock() with tryLock(timeout) and a retry.
Common misconception: Candidates often treat the conditions as symptoms to detect. They are a prevention checklist: find the condition you can remove, and the bug becomes structurally impossible instead of unlikely.
Why does the JVM not kill or restart a deadlocked program?+
There is no watchdog and no victim selection. Threads simply block, the process stays alive, and the death is silent until you ask for a thread dump or a ThreadMXBean check. A database kills a victim to keep the rest of the system moving; a JVM cannot roll an arbitrary thread back, so it does not try.
How do you prove a deadlock from a thread dump?+
Take three dumps a few seconds apart. When HotSpot detects monitors waiting on each other it prints Found one Java-level deadlock with the cycle; the proof is the same blocked threads on the same waiting-for frames in all three samples. Then map the monitor addresses to the lines that lock them.
For programmatic detection, ThreadMXBean.findDeadlockedThreads() (since Java 6) returns the thread ids in a monitor or ownable-synchronizer cycle, so a health endpoint can fail fast instead of waiting for the next human to attach.
How does global lock ordering work, and when is it not available?+
Define a total order on the lockable objects, typically an immutable id, and acquire every lock in ascending order, ideally through one helper so no call site can drift. It is unavailable when the lock set is dynamic or the objects come from a library with no key you control; then bound the wait with tryLock, or collapse the locks into one.
What does tryLock(timeout) change, and what new failure mode does it introduce?+
A failed tryLock returns false instead of waiting forever, so a thread can release what it holds and try again: the indefinite hold disappears. The new failure is livelock, where every thread keeps failing and retrying on the same schedule; a randomized backoff with jitter prevents it.
Follow-up: The natural follow-up: why must the failed attempt release the first lock before retrying? Because holding it is what closes the cycle for the other thread.
Requests hang under load, but no dump reports a deadlock. Where do you look?+
Your task graph. A fixed pool whose tasks submit to the same pool and wait on Futures can deadlock with every thread WAITING and no monitor cycle anywhere. Look for nested submissions and pools sized for the wrong kind of work, then separate the pools, stop waiting inside pool tasks, or move to virtual threads.