Thread problems
Three dumps from a live JVM: the deadlock the JVM names, four of four threads parked on a call with no timeout, and five threads blocked behind one slow lock holder.
Three thread problems account for most of the "the service is up but not answering" incidents in Java: a deadlock, a thread pool exhausted by work that never finishes, and contention on a lock that one slow holder keeps. They produce the same symptom — requests hang, CPU is low — and one tool tells them apart in under a minute: the thread dump.
Each dump in this lesson was taken with jcmd <pid> Thread.print from a small program running on Java 21 that reproduces the problem.
Reading a thread dump
A dump lists every thread with its name, its state, and its stack. The states that matter:
| state | means | in an incident, usually |
|---|---|---|
RUNNABLE | executing, or in a native call such as a socket read | busy CPU — or blocked in I/O the JVM cannot see |
BLOCKED (on object monitor) | waiting to enter a synchronized block another thread holds | contention, or a deadlock |
WAITING (parking) / TIMED_WAITING | waiting on a lock, a condition, a future, a queue, or sleeping | an idle pool thread — or one stuck waiting on something that never comes |
Name your threads. A dump full of pool-7-thread-3 tells you nothing about which pool is exhausted. Every executor should get a thread factory with a meaningful prefix.
Deadlock
Two transfers between the same two accounts, in opposite directions, each locking its source account first:
static void transfer(String name, Object from, Object to) {
synchronized (from) {
sleep(100);
synchronized (to) { System.out.println(name + " done"); }
}
}transfer-1041 locks A and waits for B; transfer-1042 locks B and waits for A. Neither will ever finish. The JVM detects monitor deadlocks itself, and the dump says so at the end:
Found one Java-level deadlock:
=============================
"transfer-1041":
waiting to lock monitor 0x0000ffff38001c10 (object 0x000000008bb14df0, a java.lang.Object),
which is held by "transfer-1042"
"transfer-1042":
waiting to lock monitor 0x0000ffff3c000f00 (object 0x000000008bb14de0, a java.lang.Object),
which is held by "transfer-1041"
Java stack information for the threads listed above:
===================================================
"transfer-1041":
at Threads.transfer(Threads.java:10)
- waiting to lock <0x000000008bb14df0> (a java.lang.Object)
- locked <0x000000008bb14de0> (a java.lang.Object)
"transfer-1042":
at Threads.transfer(Threads.java:10)
- waiting to lock <0x000000008bb14de0> (a java.lang.Object)
- locked <0x000000008bb14df0> (a java.lang.Object)
Found 1 deadlock.Everything is there: the two threads, the object each holds (locked <…de0>, locked <…df0>), the object each wants, and the line where they are stuck. The cycle is visible by matching the addresses.
The fix is structural: acquire locks in a consistent order — for example, always lock the account with the lower id first, whichever direction the money moves. With ReentrantLock, tryLock with a timeout turns a permanent hang into a failure you can retry. The JVM's detector also finds deadlocks between ReentrantLocks, which it reports as "ownable synchronizers"; it cannot see a deadlock spread across two processes or two database transactions, which the database reports on its own side.
Pool exhaustion
A request pool of four threads. Each request calls a pricing service with no timeout, and the pricing service has stopped answering. Two hundred requests arrive:
queued behind the pool: 196Four requests are being "processed" and 196 are waiting for a thread. Every thread in the pool is in the same place:
"http-nio-8080-exec-1" #20 [94] prio=5 os_prio=0 cpu=0.26ms elapsed=2.17s tid=0x0000ffffa037f950 nid=94 waiting on condition [0x0000ffff3fffd000]
java.lang.Thread.State: WAITING (parking)
at jdk.internal.misc.Unsafe.park(java.base@21.0.12/Native Method)
- parking to wait for <0x000000008bb14ff8> (a java.util.concurrent.CountDownLatch$Sync)
at java.util.concurrent.locks.LockSupport.park(java.base@21.0.12/LockSupport.java:221)
...
at java.util.concurrent.CountDownLatch.await(java.base@21.0.12/CountDownLatch.java:230)
at Threads.callPricingService(Threads.java:17)threads parked in callPricingService: 4The diagnosis is the count: every thread of one pool parked in the same frame. cpu=0.26ms confirms none of them is doing work. In a real service the frame would be a socket read inside an HTTP client or a JDBC driver — the thread's state is often RUNNABLE there, because the JVM counts a blocking native read as running, so read the frame, not only the state.
The CPU is idle, the process is healthy, the health check may still pass, and the service is completely unavailable. The fixes, in order of importance:
- A timeout on every outbound call — connect timeout and read timeout — so a dead dependency returns threads within seconds.
- A bulkhead: a separate, bounded pool for each dependency, so a failing pricing service exhausts the pricing pool rather than the request threads that also serve every other endpoint.
- A circuit breaker that stops calling a dependency that is timing out, and fails fast instead.
- A bounded queue in front of the pool, so excess work is rejected rather than accumulated — the backpressure lesson's point.
The database connection pool is the same problem one layer down. The slow APIs lesson shows its evidence from the pool's side.
Lock contention
Six worker threads write to an audit log guarded by one synchronized lock, and one write takes five seconds while holding it:
"order-worker-1" #20 [142] ... waiting on condition
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(java.base@21.0.12/Thread.java:509)
at Threads.sleep(Threads.java:13)
at Threads.writeAudit(Threads.java:20)
"order-worker-2" #21 [143] ... waiting for monitor entry
java.lang.Thread.State: BLOCKED (on object monitor)
at Threads.writeAudit(Threads.java:20)
- waiting to lock <0x000000008bb15030> (a java.lang.Object)
"order-worker-3" #22 [144] ... waiting for monitor entry
java.lang.Thread.State: BLOCKED (on object monitor)
at Threads.writeAudit(Threads.java:20)
- waiting to lock <0x000000008bb15030> (a java.lang.Object)And the whole dump summarised by state:
5 java.lang.Thread.State: BLOCKED (on object monitor)
8 java.lang.Thread.State: RUNNABLE
1 java.lang.Thread.State: TIMED_WAITING (parking)
2 java.lang.Thread.State: TIMED_WAITING (sleeping)
1 java.lang.Thread.State: WAITING (on object monitor)Five threads BLOCKED waiting for the same object, <0x000000008bb15030>, and one thread holding it while it sleeps. That is not a deadlock — it will clear when the holder finishes — but it serialises six threads' work behind the slowest one. Counting states with grep | sort | uniq -c is a quick first look at any dump; a large BLOCKED count on one address is the finding.
The fix is almost always to do less inside the lock: hold it for the in-memory state change only, and move I/O — the write, the network call, the sleep before a retry — outside it. Where a single writer is really required, hand the work to a queue and one dedicated thread, so callers never wait for the I/O at all.
Taking dumps in production
- Take three, a few seconds apart. A thread in the same frame every time is stuck; one in different frames is busy. One dump cannot tell the difference.
jcmd <pid> Thread.printworks on a running JVM without stopping it for more than a moment.kill -3 <pid>writes the same dump to the process's standard output, which is useful whenjcmdis not in the container image.- Spring Boot Actuator's
/actuator/threaddumpreturns the same information over HTTP, and should be exposed only on a management port that is not public. - Capture before restarting. A restart makes the symptom go away and takes every thread's stack with it.
Under the hood: how the JVM finds a deadlock, and what "BLOCKED" actually costs
The JVM's deadlock detector does not guess — it builds a graph. Every thread waiting on a monitor is an edge from that thread to whichever thread currently owns the monitor; a thread holding a monitor and waiting on another is a second edge out of it. Thread.print's deadlock check walks this wait-for graph and reports a deadlock exactly when it finds a cycle: a path of "waiting for" edges that returns to where it started. That is a textbook graph-cycle detection problem, and it is why the report can name the exact threads and locks involved rather than merely observing that things look stuck — the JVM has already computed the cycle, not inferred it from symptoms. The same detector also covers java.util.concurrent.locks.Lock implementations (ReentrantLock, ReentrantReadWriteLock) via the "ownable synchronizers" it tracks separately from monitors, which is why Thread.print can find a ReentrantLock deadlock even though synchronized and ReentrantLock are different mechanisms under the hood.
What it explicitly cannot see is a cycle that leaves the JVM: two services each waiting on a lock the other holds in a different process, or two database transactions each waiting on a row the other has locked. Those need their own detectors — PostgreSQL and MySQL run their own wait-for-graph cycle detection over row locks, independently of the JVM, which is exactly why a database deadlock surfaces as an exception rather than a JVM-reported deadlock.
Why BLOCKED is expensive even without a deadlock. A synchronized block in the JVM is backed by an object's monitor, and HotSpot implements monitor acquisition in tiers for performance: an uncontended lock uses a cheap thin (lightweight) lock, resolved with a compare-and-swap instruction in the acquiring thread's own stack frame and no operating-system involvement at all (an older optimisation, biased locking, skipped even that CAS for a lock repeatedly acquired by the same thread, but it was disabled by default from JDK 15 onward — JEP 374 — because its benefit had shrunk as CAS got cheaper on modern hardware and its bookkeeping cost was no longer worth it). Only once there is real contention — a second thread actually trying to enter while the first holds it — does the JVM inflate the monitor to a "fat" lock backed by an OS-level mutex, at which point the waiting thread is parked by the operating system and shows up as BLOCKED (on object monitor) in a dump. That inflation is not free (it is one reason the lock-contention section's slow holder hurts more than the raw wait time suggests: every contending thread pays the cost of parking and later being woken by the OS scheduler, not just the five seconds the holder was slow) — which is part of why "do less inside the lock" is the fix that actually helps: it keeps contention rare enough that the expensive inflated path is rarely reached at all.
Try it yourself
Trace a wait-for graph by hand
Three threads, three locks. From a dump: T1 holds lockA and is BLOCKED waiting for lockB. T2 holds lockB and is BLOCKED waiting for lockC. T3 holds lockC and is RUNNABLE, doing ordinary work, not waiting on anything.
Draw the wait-for graph in your head (or on paper) and decide: is this a deadlock? What would have to change about T3 for it to become one?
Why three locks in a row is not automatically a deadlock
The wait-for graph here is a straight line, not a cycle: T1 → T2 (waiting for a lock T2 holds), T2 → T3 (waiting for a lock T3 holds), and T3 points nowhere — it is not waiting on anything, so the chain terminates. T1 and T2 are both stalled, potentially for a long time if T3 is slow, which is a real contention problem worth investigating, but it is not a deadlock: once T3 finishes and releases lockC, T2 can proceed, then T1. It becomes a deadlock only if T3 is also blocked waiting for a lock that traces back to T1 or T2 — for example if T3 were waiting for lockA, which T1 holds, closing the cycle T1 → T2 → T3 → T1. The JVM's detector is doing exactly this check: not "are threads blocked", which is common and often fine, but "does the graph close a loop", which is the only condition under which none of the threads involved can ever make progress on their own.
Misconceptions
- "A thread stuck in
BLOCKEDstate for a long time is always a deadlock." It is contention, which is far more common and resolves on its own once the holder finishes — as the lock-contention section shows, five threadsBLOCKEDbehind one slow holder is not a deadlock, and treating it like one (restarting the service, say) fixes nothing that a faster holder wouldn't have fixed itself. - "More threads in the pool fixes a hang." If threads are hanging because a dependency never responds (pool exhaustion) or because they are all queued for the same lock (contention), adding threads adds more things waiting for the same unavailable resource — it can make the underlying problem worse by increasing load on whatever the threads are ultimately blocked on, while making the dashboard look like there is "more capacity".
Sources
- Brian Goetz et al., Java Concurrency in Practice — monitor implementation, lock contention, and deadlock avoidance by lock ordering.
- Oracle, Java Language Specification §17 (Threads and Locks) and HotSpot documentation on biased/lightweight/heavyweight locking.
jcmd/jstackdiagnostic command documentation, JDK 21.