Sub topic 13
Thread dumps and lock contention
This chapter assumes you can read a Java stack trace, know what a thread and a monitor lock are, and have used jcmd to attach to a running JVM (covered earlier in this tutorial). You will learn to capture thread dumps, read thread states, spot lock contention, and confirm it with Java Flight Recorder (JFR) events.
Why threads matter for performance
A program can be slow while the CPU sits idle. When many threads wait for one lock, throughput drops and latency rises, yet a CPU profile shows little work. A thread dump shows what every thread is doing at one moment, so it answers the question "what is everyone waiting for?"
Lock contention happens when a thread tries to enter a synchronized block or acquire a java.util.concurrent lock that another thread holds. The waiting thread cannot make progress until the owner releases the lock.
Capturing a thread dump
A thread dump is a text listing of all Java threads with their states and stack traces. Use jcmd, which is the preferred tool:
jcmd <pid> Thread.print > threads.txtjstack <pid> gives similar output. On Linux, kill -3 <pid> makes the JVM print a dump to its standard output.
For java.util.concurrent locks, add -l to include lock information:
jcmd <pid> Thread.print -l > threads-locks.txtA single dump is a snapshot. A thread that shows up as blocked once may be unlucky timing. Take three to five dumps, five to ten seconds apart, and look for threads stuck at the same place each time.
Thread states
The JVM reports each thread in one of these states.
| State | Meaning | Usually a problem? |
|---|---|---|
| RUNNABLE | Running or ready to run, including threads in native I/O | Only if it is the same hot code in every dump |
| BLOCKED | Waiting to enter a `synchronized` block or method | Yes, when many threads share one lock |
| WAITING | Waiting with no timeout, for example `Object.wait()` or `LockSupport.park()` | Often normal for idle pool threads |
| TIMED_WAITING | Waiting with a timeout, for example `sleep` or `poll` | Often normal |
Two details cause confusion. First, a thread blocked on a ReentrantLock shows as WAITING (parked), not BLOCKED. Only synchronized produces BLOCKED. Second, a thread reading from a socket shows RUNNABLE even though it does no CPU work. A dump full of RUNNABLE threads in SocketInputStream.read means the application is waiting on the network, not computing.
A program that contends
This program has eight threads that all increment a counter through one shared lock, doing a small amount of work inside the lock.
public class Contended {
private static final Object LOCK = new Object();
private static long counter = 0;
static void work() {
synchronized (LOCK) {
counter++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) throws Exception {
for (int i = 0; i < 8; i++) {
Thread t = new Thread(() -> {
while (true) {
work();
}
}, "worker-" + i);
t.setDaemon(true);
t.start();
}
Thread.sleep(60_000);
System.out.println(counter);
}
}Run it, then capture a dump with jcmd <pid> Thread.print. You will see output like this for the waiting threads:
"worker-3" #24 daemon prio=5 os_prio=0 tid=0x00007f... nid=0x4a3b waiting for monitor entry [0x00007f...]
java.lang.Thread.State: BLOCKED (on object monitor)
at Contended.work(Contended.java:7)
- waiting to lock <0x000000076ab62208> (a java.lang.Object)
at Contended.lambda$main$0(Contended.java:21)
at java.lang.Thread.run(Thread.java:834)The owner of the lock appears in a different entry:
"worker-0" #21 daemon prio=5 ... sleeping
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at Contended.work(Contended.java:10)
- locked <0x000000076ab62208> (a java.lang.Object)Match the address after waiting to lock with the address after locked. That pairing identifies the lock, its owner, and the code the owner is running while everyone else waits. Here the owner sleeps while holding the lock, which is the bug.
Reading a dump efficiently
- Count threads by state. Many BLOCKED threads point to contention.
- Group BLOCKED threads by the lock address in
waiting to lock. - Find the owner by searching for the same address after
locked. - Read the owner's stack. It is either doing slow work inside the lock (I/O, sleeping, a remote call) or is itself waiting for another lock.
- Compare several dumps. A consistent owner and location is a finding. A changing one suggests general busyness.
Ignore threads that belong to the JVM itself (GC workers, compiler threads) and idle pool threads parked on a queue.
Deadlocks
A deadlock occurs when two threads each hold a lock the other needs. The JVM detects deadlocks on monitors and ownable synchronizers, and Thread.print reports them at the end of the dump:
Found one Java-level deadlock:
=============================
"thread-A":
waiting to lock monitor 0x... (object 0x..., a java.lang.Object),
which is held by "thread-B"
"thread-B":
waiting to lock monitor 0x... (object 0x..., a java.lang.Object),
which is held by "thread-A"A deadlock shows the same two stacks in every dump and no progress. Fix it by acquiring locks in one consistent global order, or by using tryLock with a timeout.
Measuring contention with JFR
A dump tells you who waits right now. JFR tells you how long threads waited in total. Record with the profile settings, which lower the reporting thresholds:
java -XX:StartFlightRecording=duration=60s,filename=contended.jfr,settings=profile -cp . ContendedThen list the relevant events:
jfr print --events jdk.JavaMonitorEnter contended.jfrUseful events:
jdk.JavaMonitorEnter: a thread waited to enter a monitor. It records the duration, the monitor class, and the thread holding it.jdk.JavaMonitorWait: a thread calledObject.wait().jdk.ThreadPark: a thread parked, which coversReentrantLockand otherjava.util.concurrentwaits.
By default JFR records only monitor waits longer than 20 ms (10 ms in the profile settings), so very short but very frequent waits may not appear. To catch them, lower the threshold in a custom settings file or use the Mission Control Lock Instances page, which aggregates the events by lock.
In JDK Mission Control, open the Lock Instances view. It lists each monitor class, how many threads waited, and the total blocked time. Sort by blocked time and open the stack trace of the top entry.
Fixing contention
Choose the fix by the cause you found.
| Cause in the dump | Typical fix |
|---|---|
| Slow work (I/O, sleep, remote call) inside the lock | Move the slow work outside the synchronized block |
| One lock guards unrelated data | Split into several locks |
| A hot counter or map | Use `LongAdder`, `AtomicLong`, or `ConcurrentHashMap` |
| Read-heavy shared state | Use immutable snapshots or `StampedLock` |
| Nested locks in inconsistent order | Fix the lock order |
Here is the earlier example with the slow part moved out of the lock, and the counter replaced with LongAdder:
import java.util.concurrent.atomic.LongAdder;
public class Fixed {
private static final LongAdder counter = new LongAdder();
static void work() {
counter.increment();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws Exception {
for (int i = 0; i < 8; i++) {
Thread t = new Thread(() -> {
while (true) {
work();
}
}, "worker-" + i);
t.setDaemon(true);
t.start();
}
Thread.sleep(60_000);
System.out.println(counter.sum());
}
}Compare the final count of both programs. Eight threads that sleep 1 ms outside any lock complete roughly eight times as many iterations as the version that sleeps inside the lock.
Common mistakes
- Treating one dump as proof. Take several and compare.
- Reading RUNNABLE as "using CPU". Threads in socket reads are RUNNABLE.
- Looking for BLOCKED threads when the code uses
ReentrantLock. Look for WAITING threads parked inLockSupport.park, and useThread.print -lto see the owner. - Blaming the waiters. The fix lives in the owner's code.
- Ignoring virtual threads. Platform-thread dumps from
Thread.printdo not list virtual threads. On JDK 21 and later usejcmd <pid> Thread.dump_to_file -format=json threads.json.
Exercise
A dump shows 40 threads in BLOCKED state, all with "waiting to lock <0x000000076ab62208>". The one thread that holds this lock is in TIMED_WAITING inside HttpClient.send. What is the likely cause, and what is the fix?
Show answer
The owner makes a remote call while holding the lock, so every other thread waits for the network. Move the remote call outside the synchronized block, or copy the state needed under the lock, release it, and then make the call. Confirm with JFR jdk.JavaMonitorEnter events that total blocked time falls after the change.
Exercise
A service uses ReentrantLock and is slow, but Thread.print shows no BLOCKED threads. Where do you look instead?
Show answer
Look for WAITING threads whose stack ends in LockSupport.park, since ReentrantLock waiters park instead of blocking on a monitor. Run jcmd <pid> Thread.print -l to see the lock owner, and check jdk.ThreadPark events in JFR for total wait time.