Java Reference ยท Concurrency
Deadlock in Java
Understand deadlock in Java: the four conditions, how lock ordering and tryLock avoid it, and how to detect a deadlock with ThreadMXBean.
A deadlock happens when two or more threads each hold a lock that another one needs and none of them can proceed. Thread A holds lock 1 and waits for lock 2; thread B holds lock 2 and waits for lock 1. Both wait forever, and the JVM does not break the cycle for you. The program does not crash: it just stops making progress, which makes deadlocks hard to notice in testing.
Deadlock needs four conditions at once: mutual exclusion, hold-and-wait, no preemption (a lock cannot be taken away) and a circular wait. Remove any one of them and deadlock is impossible. In practice you remove the circular wait by always taking locks in the same order, or you remove hold-and-wait by using timed tryLock().
This page is a concept page. The examples are written so that they always finish: the first provokes a deadlock safely and detects it, the second shows the fix.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
There is no deadlock API, but these tools help you find and avoid it:
ThreadMXBean mx = ManagementFactory.getThreadMXBean(); long[] ids = mx.findDeadlockedThreads(); // monitors and ownable synchronizers, or null long[] monitorIds = mx.findMonitorDeadlockedThreads(); // monitors only ThreadInfo[] info = mx.getThreadInfo(ids, true, true); boolean ok = lock.tryLock(timeout, TimeUnit.MILLISECONDS); lock.lockInterruptibly();
| Tool | Description |
|---|---|
findDeadlockedThreads() |
Returns the ids of threads in a deadlock cycle involving synchronized or java.util.concurrent locks, or null. |
getThreadInfo(ids, true, true) |
Shows which lock each thread waits for and which it holds. |
jstack <pid> / jcmd <pid> Thread.print |
Prints thread dumps; the JVM appends "Found one Java-level deadlock" when it sees a cycle. |
tryLock(time, unit) |
Waits for a lock only for a limited time. |
lockInterruptibly() |
Lets another thread cancel a waiting attempt with interrupt(). |
Usage notes
- Lock ordering is the simplest cure: define one global order (by id, by hash, by name) and always acquire locks in it. Two accounts, two resources, two files: sort first.
- Hold locks briefly and never call unknown code (callbacks, listeners, overridable methods) while holding one; the callee may take another lock.
synchronizedcannot time out. If you cannot guarantee an order, useReentrantLock.tryLock()and release everything on failure.- Nested monitors on
thisare a classic source: two objects that call each other's synchronized methods can deadlock. - Deadlock is not the only stall: livelock (threads keep reacting to each other without progress) and starvation (a thread never gets a turn) look similar but have different fixes.
- Thread pools can deadlock too: a task that waits for the result of another task submitted to the same, full pool blocks forever.
- Detection is diagnosis, not recovery. The JVM cannot kill a thread safely; restart the service after fixing the lock order.
- Class initialization can deadlock when two classes' static initializers wait for each other in different threads.