Deadlock
A deadlock is a standstill where each thread waits for a lock another thread holds. Nobody can move. The JVM does not break it for you.
Detailed Explanation
Thread A holds lock 1 and wants lock 2. Thread B holds lock 2 and wants lock 1. Both wait forever. That is the classic cycle. More than two locks and more than two threads can form the same cycle. Waiting on a BlockingQueue that will only be filled by a task queued on the same saturated pool is a deadlock too, even without two monitors.
Four conditions appear in textbooks: exclusive locks, hold-and-wait, no preemption, and a circular wait. You break the cycle. The practical Java rule is lock ordering: every thread that needs lock 1 and lock 2 acquires them in the same order. If you cannot order them, do not hold one while waiting for the other: release, then try both, or use tryLock with a timeout and back off.
jstack or a thread dump shows Found one Java-level deadlock and the monitors. Learn to read it. Synchronized methods on two objects that call each other (a.transfer(b) / b.transfer(a)) are a factory for this dump.
You reach for this analysis when a system "freezes" under load and CPU is idle. You prevent it with one lock instead of two, with lock ordering, with lock-free concurrent collections, and with not calling foreign code while you hold a lock (that code may want a lock you already need, or a lock another thread holds while calling you).
The cost of a timeout-and-retry scheme is complexity and livelock if everyone retries in lockstep. The cost of a global lock order is a document people must follow. The cost of ignoring it is an outage that looks like a hang.
Virtual threads can deadlock the same way on synchronized or ReentrantLock. A barrier or latch with the wrong party size is a deadlock without a cycle of two monitors: everyone waits for a signal that only a waiting thread could send.
Code Examples
public class Ordered {
private final Object a = new Object();
private final Object b = new Object();
public void both() {
Object first = System.identityHashCode(a) < System.identityHashCode(b) ? a : b;
Object second = first == a ? b : a;
synchronized (first) {
synchronized (second) {
System.out.println("ok");
}
}
}
public static void main(String[] args) {
new Ordered().both(); // prints: ok
}
}Do not run as a test of liveness; this is the anti-pattern.
// Do not run as a test of liveness; this is the anti-pattern.
class Account {
void transferDeadlock(Account other) {
synchronized (this) {
synchronized (other) {
// if two accounts call transfer on each other, they deadlock
}
}
}
}Common Gotchas
Calling out while holding a lock invites deadlock
the callee may lock in the opposite order.
Thread dumps name the monitors
take one before you restart a frozen JVM.
`tryLock` without a backoff plan can livelock
`tryLock` without a backoff plan can livelock