Path 3 · lesson 4 of 6
Locks: ReentrantLock, ReadWriteLock and StampedLock
What java.util.concurrent.locks adds to synchronized, when read locks and optimistic reads pay off, and how threads waiting for these locks look in a thread dump and in JFR.
What you will learn
- Write the lock / try / finally pattern and say what goes wrong without it
- Use tryLock, timed tryLock and lockInterruptibly to put a limit on waiting, which synchronized cannot do
- Decide from the length of the read section whether a read-write lock helps or only adds cost
- Write a StampedLock optimistic read that copies, validates and falls back
- Recognise threads waiting for java.util.concurrent locks in a thread dump and find the owner with
jcmd Thread.print -l - Find lock waits in JFR, where they are
jdk.ThreadParkevents and notjdk.JavaMonitorEnter
Before you start
The concept
A synchronized block gives you one thing: mutual exclusion that begins and ends with a block of code. A thread that wants the monitor waits for it with no time limit, cannot be interrupted while it waits, and cannot ask whether the monitor is free. The package java.util.concurrent.locks provides locks as ordinary objects with methods, and those methods remove each of these limits.
| Lock | What it adds | What it costs |
|---|---|---|
ReentrantLock | tryLock(), tryLock(timeout), lockInterruptibly(), an optional fair queue, and any number of Condition objects per lock. | You must call unlock() yourself, in finally. The owner is not shown in a plain thread dump. |
ReentrantReadWriteLock | A pair of locks. Many threads may hold the read lock at once. The write lock is exclusive. | Taking the read lock is itself a write to shared lock state. A reader cannot upgrade to the write lock. Holders of the read lock are invisible in a thread dump. |
StampedLock | A write lock, a read lock and an optimistic read that takes no lock at all: read, then check that no writer came in. | Not reentrant, no owner, no Condition. The optimistic section may see half-updated data, so it must copy, validate and only then use. |
The price of the extra control is that the compiler no longer releases the lock for you. Every acquisition is followed at once by try, and the release goes in finally:
lock.lock();try { // read and write the state this lock guards} finally { lock.unlock();}if (lock.tryLock(200, TimeUnit.MILLISECONDS)) { // throws InterruptedException try { // got it within 200 ms } finally { lock.unlock(); }} else { // did not get it: fail fast, serve a cached value, or report "busy"}Why it is written this way
lock()is outside thetry. If it were inside and threw,finallywould callunlock()on a lock this thread does not hold, which throwsIllegalMonitorStateExceptionand hides the first error.- Nothing goes between
lock()andtry. An exception thrown there would leave the lock held for ever, because nofinallycovers it. - With
tryLock,unlock()is called only on the branch that acquired the lock.
Why it exists
Most production problems with locks are not about correctness. They are about waiting without a limit. One thread holds a lock while it calls a slow database or a remote service. Every other request that needs the lock queues behind it. With synchronized those threads cannot give up: the request thread pool fills, health checks time out, and the instance is restarted. A timed tryLock turns the same situation into a fast, visible failure for some requests while the rest of the service keeps answering.
- A limit on waiting.
tryLock(timeout)returnsfalsewhen time runs out. The caller can answer 503, use a stale value or skip the work. - Cancellation.
lockInterruptibly()and timedtryLockstop waiting when the thread is interrupted, for example when an executor is shut down or a request is cancelled. A thread blocked on a monitor ignores interrupts until it gets the monitor. - Skipping instead of queueing.
tryLock()with no arguments is the natural way to say: if someone else is already refreshing this cache, I do not need to. - More than one wait set. A monitor has one
wait/notifyset. AReentrantLockcan have severalConditionobjects, such as not-full and not-empty, so a signal reaches a thread that can use it. - Virtual threads on Java 21. A virtual thread that blocks inside
synchronizedpins its carrier thread. The Oracle guide for JDK 21 recommends guarding long, frequent I/O withReentrantLockfor that reason. Short in-memory sections can staysynchronized.
How it works inside
One int and a queue
ReentrantLock and ReentrantReadWriteLock are built on AbstractQueuedSynchronizer (AQS). AQS keeps one atomically updated int called the state, and a first-in-first-out queue of waiting threads. For ReentrantLock the state is the hold count: 0 means free, 1 means held, 2 means the owner has locked it twice. Acquiring is a compare-and-set of the state from 0 to 1. If that fails, the thread adds itself to the queue and calls LockSupport.park, which takes it off the CPU until another thread unparks it. unlock() lowers the state and unparks the first thread in the queue.
That is why a thread waiting for one of these locks is never BLOCKED. Thread.State.BLOCKED is reserved for threads waiting to enter a monitor. A parked thread is WAITING, or TIMED_WAITING if it parked with a timeout.
Fair and non-fair
By default the lock is non-fair: a thread that calls lock() at the moment the lock is released may take it ahead of threads that have been parked for a long time. This is called barging. It is fast because the barging thread is already running, while waking a parked thread costs a context switch during which the lock would sit idle. new ReentrantLock(true) makes the lock fair: it is handed to the longest-waiting thread. The API documentation warns that fair locks are often much slower, and that the untimed tryLock() ignores fairness and takes a free lock even when others are queued. Use tryLock(0, TimeUnit.SECONDS) if you need a non-waiting attempt that respects the queue.
Program outputjava -XX:ActiveProcessorCount=2 -Xmx128m LocksBench.java
Real JVM output8 threads, 2 CPUs, 1 write per 100 operations, 1 s per run ... Short read: one lookup while holding the lock synchronized 21,092,992 operations/s ReentrantLock 19,364,800 operations/s ReentrantReadWriteLock 23,219,712 operations/s StampedLock optimistic read 126,170,432 operations/s optimistic reads that failed validate() and fell back to a read lock: 83,759 of 126,170,432 operations ... Longer read: sum 2,000 prices while holding the lock synchronized 911,552 operations/s ReentrantLock 713,920 operations/s ReentrantReadWriteLock 558,848 operations/s StampedLock optimistic read 1,971,968 operations/s optimistic reads that failed validate() and fell back to a read lock: 10,012 of 1,971,968 operations ... Blocking read: the reader waits 1 ms while holding the lock synchronized 801 operations/s ReentrantLock 823 operations/s ReentrantReadWriteLock 7,119 operations/s StampedLock optimistic read 7,008 operations/s optimistic reads that failed validate() and fell back to a read lock: 483 of 7,008 operations ... Fairness: 8 threads take one ReentrantLock in a loop for 1 s new ReentrantLock() 26,679,730 acquisitions/s fewest per thread 3,161,952 most per thread 3,791,635 new ReentrantLock(true) 1,470,684 acquisitions/s fewest per thread 132,452 most per thread 259,779
synchronized, ReentrantLock and ReentrantReadWriteLock are in the same range, and the read-write lock is not ahead. The machine was shared, and repeated runs moved these three figures by a factor of 2 to 3, so do not rank them. Blocking read: when a reader holds the lock for 1 ms, the exclusive locks manage about 800 operations per second (one reader at a time) and the read-write lock about 7,100 (eight readers at once). Optimistic read: fastest in the first two cases because a read takes no lock; 83,759 of 126 million reads failed validate() and were repeated under a read lock. Fairness: the fair lock did 1.5 million acquisitions per second against 26.7 million, 18 times fewer.When readers help
A read-write lock lets readers overlap, but it does not make reading free. Taking the read lock is a compare-and-set on the shared state, and releasing it is another. With many cores, that state is a contended memory location that every reader writes to. So the read lock pays off only when the time spent inside the read section is large compared with the cost of taking the lock. The ReentrantReadWriteLock documentation says this is typically worthwhile only when the collection is large, is accessed by more readers than writers, and the operations cost more than the synchronization.
| Read section | Read-write lock | Better choice |
|---|---|---|
A HashMap.get, tens of nanoseconds | No gain. In the run above it was level with a plain lock. | ConcurrentHashMap, or an immutable map in a volatile field that writers replace |
| A scan over thousands of entries, microseconds | Gain only with enough CPUs for readers to overlap. On 2 CPUs there was none. | StampedLock optimistic read if the data is plain fields or arrays |
| A section that takes milliseconds or blocks | Large gain: readers overlap instead of queueing. | A read-write lock, or better, do not block while holding a lock |
- No upgrade. A thread that holds the read lock and asks for the write lock waits for all readers to leave, including itself. It never returns. Release the read lock first, take the write lock, and check the state again.
- Downgrade works. A thread holding the write lock may take the read lock and then release the write lock.
- Writers can starve, and so can readers. In the default non-fair mode the documentation leaves the order unspecified and says a continuously contended lock may postpone a reader or writer indefinitely. OpenJDK 21 makes a newly arriving reader wait when a writer is at the head of the queue, so one long reader plus one waiting writer stops all new readers too. The thread dump below shows exactly that.
- Conditions exist only for the write lock.
readLock().newCondition()throwsUnsupportedOperationException.
StampedLock and the optimistic read
StampedLock returns a long stamp from every acquisition and wants it back on release. Its third mode is the reason to use it. tryOptimisticRead() returns a stamp without taking any lock and without writing to shared memory. The reader copies the fields it needs into local variables, then calls validate(stamp). If no thread has taken the write lock since the stamp was issued, the copies are consistent and can be used. If validation fails, the reader repeats the read under a real read lock.
- Between
tryOptimisticRead()andvalidate()the data may be changing under you. Only read fields into locals there. Do not follow references into structures that are unsafe to read during a write, such as aHashMapbeing resized, and do not act on the values before validating. StampedLockis not reentrant. A thread that holds the write lock and calls a method that takes it again waits for itself.- It has no owner: a stamp can be released by another thread. That also means a thread dump can never name the holder.
- Its
asReadLock()andasWriteLock()views do not supportCondition. tryConvertToWriteLock(stamp)is the one supported form of upgrade: it succeeds only if it can be done immediately, and returns 0 otherwise.
What the thread dump shows
Waiting for a monitor (synchronized)
- State
BLOCKED (on object monitor) - waiting to lock <0x…> (a com.example.Account)- The owner's stack shows
- locked <0x…>with the same address - JFR event
jdk.JavaMonitorEnter, summarised byjfr view contention-by-site
Waiting for a java.util.concurrent lock
- State
WAITING (parking)orTIMED_WAITING (parking) - parking to wait for <0x…> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)- The owner is listed only with
-l, underLocked ownable synchronizers. Read-lock holders andStampedLockholders are never listed - JFR event
jdk.ThreadPark. The contention views do not include it
Thread dumpjcmd <pid> Thread.print -l (LocksParked.java: one ReentrantLock, one holder, two waiters, one Condition)
Real JVM output"price-refresh" #19 [7332] prio=5 os_prio=0 cpu=0.10ms elapsed=3.39s tid=0x0000798c384c6390 nid=7332 waiting on condition [0x0000798bcaefd000] java.lang.Thread.State: TIMED_WAITING (sleeping) ... at LocksParked.sleep(LocksParked.java:67) at LocksParked.lambda$main$0(LocksParked.java:26) ... Locked ownable synchronizers: - <0x00000000ff764110> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) ... "price-reader-lock" #20 [7333] prio=5 os_prio=0 cpu=0.12ms elapsed=3.19s tid=0x0000798c384c7580 nid=7333 waiting on condition [0x0000798bcadfd000] java.lang.Thread.State: WAITING (parking) at jdk.internal.misc.Unsafe.park(java.base@21.0.13/Native Method) - parking to wait for <0x00000000ff764110> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) ... at java.util.concurrent.locks.ReentrantLock.lock(java.base@21.0.13/ReentrantLock.java:322) at LocksParked.lambda$main$1(LocksParked.java:30) ... Locked ownable synchronizers: - None ... "price-reader-trylock" #21 [7334] prio=5 os_prio=0 cpu=0.13ms elapsed=3.19s tid=0x0000798c384dacf0 nid=7334 waiting on condition [0x0000798bcacfd000] java.lang.Thread.State: TIMED_WAITING (parking) at jdk.internal.misc.Unsafe.park(java.base@21.0.13/Native Method) - parking to wait for <0x00000000ff764110> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) ... at java.util.concurrent.locks.ReentrantLock.tryLock(java.base@21.0.13/ReentrantLock.java:479) at LocksParked.lambda$main$2(LocksParked.java:35) ... "queue-consumer" #22 [7335] prio=5 os_prio=0 cpu=0.59ms elapsed=3.19s tid=0x0000798c384dbef0 nid=7335 waiting on condition [0x0000798bcabfd000] java.lang.Thread.State: WAITING (parking) at jdk.internal.misc.Unsafe.park(java.base@21.0.13/Native Method) - parking to wait for <0x00000000ff764160> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject) ... at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitUninterruptibly(java.base@21.0.13/AbstractQueuedSynchronizer.java:1699) at LocksParked.lambda$main$3(LocksParked.java:41)
price-reader-lock is WAITING (parking) and is parking to wait for <0x00000000ff764110>. Search the dump for that address: it appears under Locked ownable synchronizers of price-refresh, which is asleep in LocksParked.java:26 while holding the lock. That section exists only because of -l. price-reader-trylock waits for the same lock but is TIMED_WAITING with tryLockNanos in its stack: it will give up. queue-consumer parks on a ConditionObject: it is waiting for a signal, holds nothing, and is normal for an idle consumer.Thread dumpThe same dump: a ReentrantReadWriteLock with one long reader
Real JVM output"catalog-reader-1" #23 [7336] prio=5 os_prio=0 cpu=0.13ms elapsed=3.19s tid=0x0000798c384dd1e0 nid=7336 waiting on condition [0x0000798bcaafd000] java.lang.Thread.State: TIMED_WAITING (sleeping) ... at LocksParked.sleep(LocksParked.java:67) at LocksParked.lambda$main$4(LocksParked.java:46) ... Locked ownable synchronizers: - None ... "catalog-writer" #24 [7343] prio=5 os_prio=0 cpu=0.14ms elapsed=2.99s tid=0x0000798c384de4e0 nid=7343 waiting on condition [0x0000798bca9fd000] java.lang.Thread.State: WAITING (parking) at jdk.internal.misc.Unsafe.park(java.base@21.0.13/Native Method) - parking to wait for <0x00000000ff7643b0> (a java.util.concurrent.locks.ReentrantReadWriteLock$NonfairSync) ... at java.util.concurrent.locks.ReentrantReadWriteLock$WriteLock.lock(java.base@21.0.13/ReentrantReadWriteLock.java:959) at LocksParked.lambda$main$5(LocksParked.java:50) ... Locked ownable synchronizers: - None ... "catalog-reader-2" #25 [7349] prio=5 os_prio=0 cpu=0.22ms elapsed=2.79s tid=0x0000798c384df750 nid=7349 waiting on condition [0x0000798bca8fd000] java.lang.Thread.State: WAITING (parking) at jdk.internal.misc.Unsafe.park(java.base@21.0.13/Native Method) - parking to wait for <0x00000000ff7643b0> (a java.util.concurrent.locks.ReentrantReadWriteLock$NonfairSync) ... at java.util.concurrent.locks.ReentrantReadWriteLock$ReadLock.lock(java.base@21.0.13/ReentrantReadWriteLock.java:738) at LocksParked.lambda$main$6(LocksParked.java:55) ... Locked ownable synchronizers: - None
catalog-writer and catalog-reader-2 both park on ReentrantReadWriteLock$NonfairSync at 0x00000000ff7643b0. No thread lists that address as an owned synchronizer: catalog-reader-1, which holds the read lock and sleeps at line 46, shows None. Read locks have no single owner, so the dump cannot name the holder. You find it by elimination: a thread that is inside the code guarded by the lock and is not itself parked on it. catalog-reader-2 only wants to read, yet it waits, because a writer is queued ahead of it.JFRjfr summary and jfr print --stack-depth 8 --events jdk.ThreadPark (LockParkJfr.java, settings=profile)
Real JVM output Event Type Count Size (bytes)
=============================================================
jdk.ThreadSleep 97 1843
jdk.ThreadPark 96 3747
jdk.JavaMonitorEnter 0 0
...
jdk.ThreadPark {
startTime = 21:45:47.108 (2026-11-15)
duration = 30.1 ms
parkedClass = java.util.concurrent.locks.ReentrantLock$NonfairSync (classLoader = bootstrap)
timeout = N/A
until = N/A
address = 0xFE6FC3D0
eventThread = "report-worker-0" (javaThreadId = 23)
stackTrace = [
jdk.internal.misc.Unsafe.park(boolean, long)
java.util.concurrent.locks.LockSupport.park(Object) line: 221
java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(AbstractQueuedSynchronizer$Node, int, boolean, boolean, boolean, long) line: 788
java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(int) line: 1024
java.util.concurrent.locks.ReentrantLock$Sync.lock() line: 153
java.util.concurrent.locks.ReentrantLock.lock() line: 322
LockParkJfr.buildReport() line: 28
LockParkJfr.lambda$main$0(long) line: 20
...
]ReentrantLock that is held for 30 ms at a time. The recording has 96 jdk.ThreadPark events and zero jdk.JavaMonitorEnter events. parkedClass names the kind of lock, duration is the time parked, and the stack gives the call site, LockParkJfr.buildReport() line: 28. On this recording jfr view contention-by-site printed No events found, because that view is built from monitor events. Park events shorter than the threshold are not recorded: 20 ms in default.jfc, 10 ms in profile.jfc.Architecture
Drawing diagram…
Flowchart. If reads are not much more common than writes, choose synchronized unless a timeout, interruption, tryLock or several conditions are needed, in which case choose ReentrantLock. If reads dominate, prefer publishing an immutable snapshot through a volatile reference. Otherwise a long or blocking read section points to ReentrantReadWriteLock, a short read of plain fields points to a StampedLock optimistic read, and anything else to ReentrantLock.
flowchart TD
A["Shared state needs mutual exclusion"] --> B{"Is the read path hot and writes rare"}
B -->|"No"| C{"Need a timeout, interruption, tryLock or several conditions"}
C -->|"No"| D["synchronized"]
C -->|"Yes"| E["ReentrantLock"]
B -->|"Yes"| F{"Can writers publish a new immutable snapshot"}
F -->|"Yes"| G["volatile reference, no lock on reads"]
F -->|"No"| H{"Is the read section long or blocking"}
H -->|"Yes"| I["ReentrantReadWriteLock"]
H -->|"No"| J{"Does the read only copy fields or array elements"}
J -->|"Yes"| K["StampedLock optimistic read"]
J -->|"No"| E- The first question is about the workload, not the API. A lock that is held briefly and rarely contended costs little whichever kind it is.
synchronizedstays the default for short in-memory sections. Reach forReentrantLockwhen a caller must be able to stop waiting, or when a virtual thread would block while holding the lock.- For read-mostly data the best lock is often none: writers build a new immutable object and publish it with one
volatilewrite.PriceCatalogin the implementation below does this and uses a lock only to stop two refreshes running at once. ReentrantReadWriteLockearns its place only when readers spend real time inside the lock.StampedLockis for small, hot, fixed-shape state such as a pair of numbers.
Step by step
Drawing diagram…
Sequence diagram. A reader obtains an optimistic stamp and copies the first field. A writer takes the write lock, changes both fields and releases. The reader copies the second field, so its two copies come from different updates. validate returns false, the reader takes a real read lock, copies both fields again, releases and only then uses the values.
sequenceDiagram participant R as Reader thread participant S as StampedLock participant W as Writer thread R->>S: tryOptimisticRead S-->>R: stamp 256, no lock taken Note over R: copies bid into a local W->>S: writeLock S-->>W: stamp 384 Note over W: writes bid and ask W->>S: unlockWrite with 384 Note over R: copies ask into a local, old bid with new ask R->>S: validate 256 S-->>R: false, a writer came in R->>S: readLock S-->>R: stamp 513 Note over R: copies bid and ask again R->>S: unlockRead with 513 Note over R: uses the consistent pair
- The stamp values are illustrative. What matters is that the reader's stamp is compared with the lock's current state: any write lock taken in between makes
validatereturnfalse. - Between the two copies the reader held an old
bidand a newask. Nothing stopped that. The protection is that the reader does not use them before validating. - In the common case there is no writer,
validatereturnstrue, and the reader never wrote to shared memory at all. That is why the optimistic read scaled best in the measurement above. - The fallback takes a real read lock, so a reader cannot be forced to retry for ever by a stream of writers.
In a real system
A multi-tenant API keeps per-tenant configuration in a cache guarded by a ReentrantReadWriteLock. After a deploy that added lazy loading on a cache miss, instances stop answering a few minutes after start. CPU is near zero. The request thread pool is full. There is no error in the log and no deadlock in the dump.
Thread dumpjcmd <pid> Thread.print -l (RwUpgrade.java: the same mistake, three request threads)
Real JVM output"http-1" #19 [661175] prio=5 os_prio=0 cpu=0.22ms elapsed=6.21s tid=0x00007888b0492af0 nid=661175 waiting on condition [0x0000788889a2d000] java.lang.Thread.State: WAITING (parking) at jdk.internal.misc.Unsafe.park(java.base@21.0.13/Native Method) - parking to wait for <0x00000000ff581b98> (a java.util.concurrent.locks.ReentrantReadWriteLock$NonfairSync) ... at java.util.concurrent.locks.ReentrantReadWriteLock$WriteLock.lock(java.base@21.0.13/ReentrantReadWriteLock.java:959) at RwUpgrade.get(RwUpgrade.java:21) ... Locked ownable synchronizers: - None ... "http-2" #20 [661177] prio=5 os_prio=0 cpu=0.30ms elapsed=6.00s tid=0x00007888b04ab900 nid=661177 waiting on condition [0x000078888992d000] java.lang.Thread.State: WAITING (parking) at jdk.internal.misc.Unsafe.park(java.base@21.0.13/Native Method) - parking to wait for <0x00000000ff581b98> (a java.util.concurrent.locks.ReentrantReadWriteLock$NonfairSync) ... at java.util.concurrent.locks.ReentrantReadWriteLock$ReadLock.lock(java.base@21.0.13/ReentrantReadWriteLock.java:738) at RwUpgrade.get(RwUpgrade.java:18) ... Locked ownable synchronizers: - None ... "http-3" #21 [661191] prio=5 os_prio=0 cpu=0.19ms elapsed=5.80s tid=0x00007888b04aca00 nid=661191 waiting on condition [0x000078888982d000] java.lang.Thread.State: WAITING (parking) at jdk.internal.misc.Unsafe.park(java.base@21.0.13/Native Method) - parking to wait for <0x00000000ff581b98> (a java.util.concurrent.locks.ReentrantReadWriteLock$NonfairSync) ... at java.util.concurrent.locks.ReentrantReadWriteLock$ReadLock.lock(java.base@21.0.13/ReentrantReadWriteLock.java:738) at RwUpgrade.get(RwUpgrade.java:18) ... Locked ownable synchronizers: - None
ReentrantReadWriteLock$NonfairSync. http-1 is in WriteLock.lock at RwUpgrade.java:21; the other two are in ReadLock.lock at line 18. Every thread shows Locked ownable synchronizers: None, and the dump has no Found one Java-level deadlock section. The clue is http-1: line 21 is inside the method, after it took the read lock at line 18. It is waiting for readers to leave and it is one of them. The readers behind it wait because a writer is queued.Program outputjava RwUpgrade.java
Real JVM outputpid 661108: read holds=1, write locked=false, queued threads=3 findDeadlockedThreads() returned null (no deadlock reported)
ThreadMXBean.findDeadlockedThreads() returns null, so an automatic deadlock check or health indicator built on it stays green while the service is dead.The second common case is a lock held across a slow call. A pricing service refreshes its price table from a remote system under a lock, and every request takes the same lock to read. The remote system slows from 200 ms to 40 s. In a thread dump almost all request threads are WAITING (parking) on one ReentrantLock$NonfairSync address, and with -l one thread owns that address and is RUNNABLE in a socket read. The fix is in the design: readers use a published snapshot and take no lock, and only one thread refreshes. PriceCatalog below is that design.
- Many threads parked on one address means one contended lock. Take the address from a
parking to wait forline and search for it underLocked ownable synchronizers. - No owner found means the dump was taken without
-l, or the lock is held in read mode, or it is aStampedLock. Then look for the thread that is inside the guarded code and not parked on the lock. TIMED_WAITING (parking)withtryLockin the stack is a caller with a limit. If you see many of these and a rising rate of timeouts, the lock is held too long, but the service is degrading instead of hanging.- A thread parked on a
ConditionObjectis waiting for a signal, not for the lock. An idle worker waiting for work looks like this and is healthy.
Java and Spring Boot
Three small classes from a pricing and inventory service, one per lock feature, and the lab program that produced the thread dump above. The Spring class was compiled with javac against stand-ins for the Spring and SLF4J types; the plain Java classes compile as they are on JDK 21.
package com.example.pricing;import java.math.BigDecimal;import java.time.Duration;import java.time.Instant;import java.util.Map;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.ReentrantLock;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Service;@Servicepublic class PriceCatalog { private static final Logger log = LoggerFactory.getLogger(PriceCatalog.class); private static final Duration MAX_AGE = Duration.ofSeconds(30); private record Snapshot(Map<String, BigDecimal> prices, Instant loadedAt) { } private final PricingClient pricingClient; private final ReentrantLock refreshLock = new ReentrantLock(); private volatile Snapshot snapshot = new Snapshot(Map.of(), Instant.EPOCH); public PriceCatalog(PricingClient pricingClient) { this.pricingClient = pricingClient; } /** Hot path: no lock at all. Readers use whatever snapshot is published. */ public BigDecimal priceOf(String sku) { if (isStale()) { refreshUnlessSomeoneElseIs(); } return snapshot.prices().get(sku); } private void refreshUnlessSomeoneElseIs() { if (!refreshLock.tryLock()) { return; // another request is already refreshing: answer from the current snapshot } try { if (isStale()) { // re-check: the previous holder may just have finished snapshot = new Snapshot(Map.copyOf(pricingClient.fetchAll()), Instant.now()); } } catch (RuntimeException e) { log.warn("price refresh failed, keeping the snapshot from {}", snapshot.loadedAt(), e); } finally { refreshLock.unlock(); } } /** Admin action: wait for a running refresh, but only for so long. */ public boolean refreshNow(Duration maxWait) throws InterruptedException { if (!refreshLock.tryLock(maxWait.toMillis(), TimeUnit.MILLISECONDS)) { return false; // the caller turns this into 503 with Retry-After } try { snapshot = new Snapshot(Map.copyOf(pricingClient.fetchAll()), Instant.now()); return true; } finally { refreshLock.unlock(); } } private boolean isStale() { return snapshot.loadedAt().plus(MAX_AGE).isBefore(Instant.now()); }}Why it is written this way
- Readers never take the lock. They read one
volatilereference to an immutableSnapshot, so a slow refresh cannot stall them. tryLock()with no arguments means: if a refresh is already running, do not queue behind it. Without it, every request that notices the stale table would wait and then refresh again.- The staleness check is repeated after the lock is taken. The thread that held the lock a moment ago may have just published a fresh snapshot.
- The remote call is made while holding
refreshLock, which is acceptable here because nothing on the request path ever waits for that lock. refreshNowuses the timed form because an operator wants either a fresh table or a clear answer within a known time.PricingClientis the service's HTTP client interface, assumed from the rest of the project.
package com.example.pricing;import java.util.concurrent.locks.StampedLock;/** Bid and ask for one currency pair. Updated a few times per second, read on every price calculation. */public class FxQuote { private final StampedLock lock = new StampedLock(); private double bid; private double ask; public void update(double newBid, double newAsk) { long stamp = lock.writeLock(); try { bid = newBid; ask = newAsk; } finally { lock.unlockWrite(stamp); } } public double mid() { long stamp = lock.tryOptimisticRead(); // no lock taken, no write to shared memory double b = bid; // copy the fields to locals first double a = ask; if (!lock.validate(stamp)) { // a writer got in: b and a may belong to different updates stamp = lock.readLock(); // fall back to a real read lock try { b = bid; a = ask; } finally { lock.unlockRead(stamp); } } return (b + a) / 2; // use the values only after validation }}Why it is written this way
- The optimistic path does three things in order: get a stamp, copy the fields to locals, validate. The values are used only after
validatereturnedtrueor the read lock was held. - The two fields are primitives. Reading them while a writer is active can give a mixed pair but cannot throw or loop, which is what makes an optimistic read safe here.
unlockReadandunlockWritetake the stamp returned by the matching acquisition. Passing a wrong stamp throwsIllegalMonitorStateException.- Nothing called from inside these methods may take the same
StampedLockagain: it is not reentrant.
package com.example.inventory;import java.time.Duration;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;/** Units of one product that can still be reserved. Callers may wait a bounded time for a restock. */public class StockGate { private final ReentrantLock lock = new ReentrantLock(); private final Condition restocked = lock.newCondition(); private int available; public StockGate(int initial) { this.available = initial; } /** Returns false if the units did not become available within maxWait. */ public boolean reserve(int units, Duration maxWait) throws InterruptedException { long nanosLeft = maxWait.toNanos(); lock.lockInterruptibly(); // a cancelled request stops waiting for the lock try { while (available < units) { // always a loop: wake-ups can be spurious, or someone else took the stock if (nanosLeft <= 0L) { return false; } nanosLeft = restocked.awaitNanos(nanosLeft); // releases the lock while waiting, re-acquires before returning } available -= units; return true; } finally { lock.unlock(); } } public void restock(int units) { lock.lock(); try { available += units; restocked.signalAll(); // waiters need different amounts, so wake them all to re-check } finally { lock.unlock(); } }}Why it is written this way
awaitNanosreleases the lock while the thread waits and takes it again before returning, so thewhilecondition is always checked with the lock held.awaitNanosreturns the time still left. Feeding it back into the loop keeps the total wait withinmaxWaitacross several wake-ups.lockInterruptiblylets a cancelled request leave the queue for the lock.lock()would keep it there.signalAllis used because waiters want different quantities. Withsignal, the one thread woken might need more than was restocked while another that could proceed stays asleep.
import java.util.ArrayDeque;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;import java.util.concurrent.locks.ReentrantReadWriteLock;/** * Extra for the lesson "locks-reentrant-readwrite-stamped": what java.util.concurrent locks look like in a thread dump. * * java LocksParked.java then, from another terminal: jcmd <pid> Thread.print -l * * One thread holds a ReentrantLock while it "calls a slow service". Others wait for it with lock(), with a timed * tryLock and on a Condition. A second group shows a ReentrantReadWriteLock: a reader holds the read lock, a writer * queues behind it, and a reader that arrives later queues behind the writer. */public class LocksParked { static final ReentrantLock priceLock = new ReentrantLock(); static final ReentrantLock queueLock = new ReentrantLock(); static final Condition notEmpty = queueLock.newCondition(); static final ArrayDeque<String> queue = new ArrayDeque<>(); static final ReentrantReadWriteLock catalogLock = new ReentrantReadWriteLock(); public static void main(String[] args) throws Exception { start("price-refresh", () -> { priceLock.lock(); try { sleep(60_000); } finally { priceLock.unlock(); } // slow remote call made while holding the lock }); sleep(200); start("price-reader-lock", () -> { priceLock.lock(); // waits with no limit try { } finally { priceLock.unlock(); } }); start("price-reader-trylock", () -> { try { if (priceLock.tryLock(45, TimeUnit.SECONDS)) priceLock.unlock(); // waits, but gives up after 45 s } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); start("queue-consumer", () -> { queueLock.lock(); try { while (queue.isEmpty()) notEmpty.awaitUninterruptibly(); // releases queueLock while it waits } finally { queueLock.unlock(); } }); start("catalog-reader-1", () -> { catalogLock.readLock().lock(); try { sleep(60_000); } finally { catalogLock.readLock().unlock(); } // a long read }); sleep(200); start("catalog-writer", () -> { catalogLock.writeLock().lock(); // must wait for every reader to leave try { } finally { catalogLock.writeLock().unlock(); } }); sleep(200); start("catalog-reader-2", () -> { catalogLock.readLock().lock(); // arrives after the writer queued try { } finally { catalogLock.readLock().unlock(); } }); sleep(300); System.out.println("pid " + ProcessHandle.current().pid() + ", threads are parked. Run: jcmd " + ProcessHandle.current().pid() + " Thread.print -l"); System.out.println("priceLock: locked=" + priceLock.isLocked() + " queued threads=" + priceLock.getQueueLength()); System.out.println("catalogLock: read holds=" + catalogLock.getReadLockCount() + " write locked=" + catalogLock.isWriteLocked() + " queued threads=" + catalogLock.getQueueLength()); sleep(60_000); System.exit(0); } static void start(String name, Runnable body) { new Thread(body, name).start(); } static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }}Why it is written this way
- This is the program behind the first two thread dumps in this lesson. The exercise asks you to run it and read your own dump.
- The
sleepcalls between thread starts only fix the order in which threads reach the locks, so the dump is the same on every run.
Wrong, then right
A tenant configuration cache in a Spring Boot service. The first version loads a missing entry while still holding the read lock. It passes every single-threaded test in which the entry is already cached.
Incorrect implementation
package com.example.tenants;import java.util.HashMap;import java.util.Map;import java.util.concurrent.locks.ReentrantReadWriteLock;import org.springframework.stereotype.Service;@Servicepublic class TenantConfigCache { private final ReentrantReadWriteLock rw = new ReentrantReadWriteLock(); private final Map<String, TenantConfig> cache = new HashMap<>(); private final ConfigClient configClient; public TenantConfigCache(ConfigClient configClient) { this.configClient = configClient; } public TenantConfig get(String tenantId) { rw.readLock().lock(); TenantConfig config = cache.get(tenantId); if (config == null) { rw.writeLock().lock(); // still holding the read lock config = configClient.load(tenantId); // HTTP call, 50 ms to several seconds cache.put(tenantId, config); rw.writeLock().unlock(); } rw.readLock().unlock(); return config; }}Why it is written this way
rw.writeLock().lock()is called while this thread holds the read lock.ReentrantReadWriteLockdoes not support that upgrade.- No
try/finally: ifconfigClient.loadthrows, neither lock is released. - The HTTP call runs under the write lock, so even if the upgrade worked, every reader would wait for the remote service.
Why it fails
- The write lock is granted only when no thread holds the read lock. The calling thread holds it, so the first cache miss parks that thread for ever, waiting for itself. The
ReentrantReadWriteLockdocumentation states that upgrading from a read lock to the write lock is not possible. - From then on a writer is queued, and OpenJDK 21 makes new readers wait behind a queued writer. Every later request parks in
readLock().lock(). In the real run above three of three threads were parked within a second; in production the request pool fills and the instance stops answering. - Nothing reports it. The dump has no deadlock section,
findDeadlockedThreads()returnsnull, and no thread is listed as owner because read holds are not owned. CPU is idle, so autoscaling does not react either. - If
loadthrows instead, the lock is left held in read mode for ever. The service keeps reading, but the nextevictor load that needs the write lock hangs, hours after the exception that caused it.
Corrected implementation
package com.example.tenants;import java.util.HashMap;import java.util.Map;import java.util.concurrent.locks.ReentrantReadWriteLock;import org.springframework.stereotype.Service;@Servicepublic class TenantConfigCache { private final ReentrantReadWriteLock rw = new ReentrantReadWriteLock(); private final Map<String, TenantConfig> cache = new HashMap<>(); private final ConfigClient configClient; public TenantConfigCache(ConfigClient configClient) { this.configClient = configClient; } public TenantConfig get(String tenantId) { rw.readLock().lock(); try { TenantConfig cached = cache.get(tenantId); if (cached != null) { return cached; } } finally { rw.readLock().unlock(); // released before anything else is asked for } TenantConfig loaded = configClient.load(tenantId); // slow call with no lock held rw.writeLock().lock(); try { TenantConfig raced = cache.putIfAbsent(tenantId, loaded); // another thread may have loaded it meanwhile return raced != null ? raced : loaded; } finally { rw.writeLock().unlock(); } } public void evict(String tenantId) { rw.writeLock().lock(); try { cache.remove(tenantId); } finally { rw.writeLock().unlock(); } }}Why it is written this way
- The read lock is released in
finallybefore the method does anything else. No path asks for the write lock while holding the read lock. - The remote call runs with no lock held. A slow configuration service delays only the requests for that missing tenant.
putIfAbsentunder the write lock is the re-check: if two threads loaded the same tenant, the first one stored wins and both return the same object.- Every
lock()is followed at once bytry, and everyunlock()is infinally, so an exception fromcacheor the client cannot leave a lock held.
Trade-offs
- Two requests that miss the same tenant at the same time both call the configuration service. The cache stays correct, but the remote system sees duplicate loads after a restart or an eviction.
- A reader pays for two lock operations on shared state per lookup. For a map lookup this is no faster than a plain lock; the measurement in this lesson showed the read-write lock level with
synchronizedfor short reads. - For this exact job
ConcurrentHashMap.computeIfAbsentis less code and loads each key once. The read-write lock version is worth keeping only if readers need a consistent view across several keys. - The corrected code is longer and the locking rules now live in the method's structure. A later edit that adds a write inside the first
trywould bring the hang back, so the class needs a test that misses the cache from several threads.
Configuration
These locks have no JVM flags. What can be set is the fairness of each lock, how much a thread dump shows, and which waits JFR records. Defaults are those of JDK 21.
new ReentrantLock(boolean fair)Default false (non-fair)
- What it does
- With
true, the lock is granted to the longest-waiting thread. Withfalse, a running thread may take a just-released lock ahead of parked threads. - When to change it
- Leave it non-fair unless you have measured starvation. In the run above the fair lock did 18 times fewer acquisitions. Untimed
tryLock()ignores this setting.
new ReentrantReadWriteLock(boolean fair)Default false (non-fair)
- What it does
- In fair mode a reader waits if any writer is queued, and a writer waits until the lock is completely free, in approximately arrival order.
- When to change it
- Consider
truewhen writers must not be delayed by a steady stream of readers and you can accept lower throughput.
jcmd <pid> Thread.print -lDefault -l is off
- What it does
- Adds a
Locked ownable synchronizerssection to every thread, listing theReentrantLocks and write locks it holds. - When to change it
- Always pass
-lwhen the dump shows threadsparking to wait fora lock. Without it you cannot find the owner.jstack -l <pid>is the matching long-listing option.
jdk.ThreadPark#threshold (JFR)Default 20 ms in default.jfc, 10 ms in profile.jfc
- What it does
- Parks shorter than this are not recorded. Waits for
ReentrantLock,ReentrantReadWriteLock,StampedLockandConditionare park events. - When to change it
- Lower it for a short investigation, for example
jcmd <pid> JFR.start settings=profile jdk.ThreadPark#threshold=1ms duration=60s filename=/tmp/park.jfr. Expect many events from idle pool threads.
jdk.JavaMonitorEnter#threshold (JFR)Default 20 ms in default.jfc, 10 ms in profile.jfc
- What it does
- The matching event for
synchronized. It does not fire forjava.util.concurrentlocks. - When to change it
- If you moved a hot section from
synchronizedtoReentrantLock, your contention dashboards built on this event go quiet. Addjdk.ThreadPark.
-Djdk.tracePinnedThreads=full|shortDefault not set
- What it does
- On JDK 21, prints a stack trace when a virtual thread blocks while pinned, for example inside
synchronized. - When to change it
- Use it to find the
synchronizedblocks that are worth converting toReentrantLockwhen you adopt virtual threads. Convert only the ones that block for long and often.
Hands-on exercise
Find the owner of a lock that the dump does not show
Run a program whose threads wait on a ReentrantLock, a Condition and a ReentrantReadWriteLock, take a thread dump with and without -l, and identify who holds what.
Steps · 0 of 6 done
What you should see
Without -l, price-reader-lock is WAITING (parking) and price-reader-trylock is TIMED_WAITING (parking) on the same ReentrantLock$NonfairSync address, and nothing names the holder. With -l, price-refresh lists that address under Locked ownable synchronizers; it is sleeping at LocksParked.java:26 inside the locked section. queue-consumer parks on a ConditionObject and holds nothing. For the read-write lock no thread lists the address even with -l: catalog-reader-1 holds the read lock and shows None. You identify it because it is inside the guarded code and not parked. catalog-reader-2 waits because catalog-writer is queued ahead of it. The program prints priceLock: locked=true queued threads=2 and catalogLock: read holds=1 write locked=false queued threads=2.
What can go wrong
unlock() outside finally
- Symptom
- After one request fails with an exception, every later request that needs the lock hangs. The dump shows threads parked on a lock whose owner, with
-l, is an idle pool thread sitting inThreadPoolExecutor.getTask. - Cause
- The exception skipped
unlock(). The pool thread went back to the pool still owning the lock. Unlike a monitor, the lock is not tied to a block and is never released for you. - Fix
lock.lock(); try { … } finally { lock.unlock(); }with nothing betweenlock()andtry. Review everylock()call for this shape.
Upgrading a read lock
- Symptom
- The service hangs on the first cache miss. All request threads park on one
ReentrantReadWriteLock$NonfairSync. No deadlock is reported and no owner is listed. - Cause
- A thread asked for the write lock while holding the read lock. The write lock waits for all readers, including the caller.
- Fix
- Release the read lock, take the write lock, re-check the condition. Or take the write lock from the start on paths that may write.
A read-write lock around a tiny read
- Symptom
- Throughput is no better than with
synchronized, or is worse on a machine with many cores. A profile shows time inReentrantReadWriteLock$Sync.tryAcquireSharedandtryReleaseShared. - Cause
- Each read acquires and releases shared lock state with compare-and-set. For a read of a few nanoseconds that bookkeeping is most of the cost, and readers contend on it.
- Fix
- Use
ConcurrentHashMap, publish immutable snapshots through avolatilefield, or use aStampedLockoptimistic read for small fixed-shape state.
Using values from an optimistic read before validate
- Symptom
- Rare impossible results: a negative spread, an index out of bounds, a total that does not match its parts. It cannot be reproduced under a debugger.
- Cause
- The code computed with, or branched on, fields read between
tryOptimisticRead()andvalidate(). A writer changed some of them in between. - Fix
- Copy to locals, call
validate, and only then compute. If validation fails, read again underreadLock().
Reentering a StampedLock
- Symptom
- A single thread hangs with no other thread involved. Its stack shows
StampedLock.writeLocktwice, once near the top and once further down. - Cause
StampedLockis not reentrant. A locked method called another method that takes the same lock.- Fix
- Pass the stamp to the inner method, or split it into a public locking method and a private one that assumes the lock is held. Use
ReentrantLockif the call graph cannot be controlled.
Making a lock fair to cure slowness
- Symptom
- After switching to
new ReentrantLock(true)the throughput drops sharply and latency rises for everyone. - Cause
- A fair lock hands over to a parked thread on every release, which adds a context switch per acquisition. The API documentation warns that fair locks are often much slower.
- Fix
- Shorten the critical section or split the lock. Use fairness only for a measured starvation problem, and measure again after.
How to troubleshoot
Requests hang, CPU is low, and many threads are WAITING (parking)
Check
jcmd <pid> Thread.print -l | grep -c 'parking to wait for' and then group the lines by address
- How to read it
- Many threads on one
ReentrantLock$…SyncorReentrantReadWriteLock$…Syncaddress is one contended lock. Many onConditionObjectorSynchronousQueueaddresses are usually idle pool threads.
Need the thread that holds a ReentrantLock or a write lock
Check
jcmd <pid> Thread.print -l then search for the waited-for address under 'Locked ownable synchronizers'
- How to read it
- The thread that lists the address is the owner. Read its stack: a socket read or JDBC call there means a slow call is made while holding the lock.
Threads park on a read-write lock and no thread owns it
Check
In the same dump, search for stack frames inside the class that uses the lock, in threads that are not parked on it
- How to read it
- The lock is held in read mode. The holder is a thread still inside the guarded code, or one that left it without unlocking. A thread in
WriteLock.lockwhose stack passes through code that already took the read lock is an upgrade attempt.
Slow requests, and you suspect waiting on a java.util.concurrent lock
Check
jcmd <pid> JFR.start settings=profile duration=60s filename=/tmp/locks.jfr then jfr print --stack-depth 12 --events jdk.ThreadPark /tmp/locks.jfr
- How to read it
- Look at events whose
parkedClassis a lock class.durationis the wait and the stack is the call site. Ignore parks onConditionObjectfrom idle workers.jfr view contention-by-sitewill not show these waits.
Want to know from inside the application how crowded a lock is
Check
ReentrantLock.getQueueLength(), isLocked(), and ReentrantReadWriteLock.getReadLockCount(), isWriteLocked()
- How to read it
- These are estimates meant for monitoring. A queue length that stays above zero means callers are waiting.
getReadLockCount()above zero with nobody reading means a read hold leaked.
Key takeaways
java.util.concurrentlocks add whatsynchronizedlacks: a non-waiting attempt, a timeout, interruption, fairness and several conditions. In exchange, releasing the lock is your job:lock(), thentry, thenunlock()infinally.- A timed
tryLockturns unlimited waiting into a fast failure. It does not shorten the critical section, so move slow calls out of the lock first. - A read-write lock helps only when the read section is long compared with the cost of taking the lock. For a map lookup it measured no better than a plain lock.
- A read lock cannot be upgraded. The attempt hangs the thread, then everything behind it, and no tool reports a deadlock.
- A
StampedLockoptimistic read takes no lock: copy to locals,validate, then use, with a read lock as fallback. It is not reentrant and has no owner. - Threads waiting for these locks are
WAITING (parking), notBLOCKED. Owners appear only withThread.print -l, and holders of read locks never appear. - In JFR these waits are
jdk.ThreadParkevents. Monitor contention views andjdk.JavaMonitorEnterdo not include them.
Practical check
Small scenarios, one decision each. Pick what you would do, then read why.
Scenario 1 of 3
A service with a 200-thread request pool stops answering. CPU is at 2%. jcmd Thread.print -l shows 199 threads WAITING (parking) on one ReentrantReadWriteLock$NonfairSync address. 198 are in ReadLock.lock and one is in WriteLock.lock. Every thread shows 'Locked ownable synchronizers: None' and there is no deadlock section.
What should you look for next?
Scenario 2 of 3
A product lookup reads one entry from a HashMap under a ReentrantLock. The read takes about 30 ns and there is one write per minute. On a 16-core host the lock is the top frame in the profile at 40,000 requests per second. A colleague proposes ReentrantReadWriteLock so that readers no longer exclude each other.
Which change is most likely to remove the bottleneck?
Scenario 3 of 3
An order service calls a fraud-check API while holding a ReentrantLock taken with lock(). The API normally answers in 80 ms. Today it takes 25 s. Within a minute all 150 request threads are WAITING (parking) on that lock, including requests that never need a fraud check, and the load balancer removes the instance.
Which change addresses the cause and limits the damage next time?
References
References: Java SE 21 API: ReentrantLock (fairness, tryLock, the lock/try/finally idiom) ↗ · Java SE 21 API: Lock (timed, interruptible and non-blocking acquisition, memory semantics) ↗ · Java SE 21 API: Condition (await in a loop, spurious wake-ups, signal and signalAll) ↗ · Java SE 21 API: ReentrantReadWriteLock (no upgrade, downgrading, fair and non-fair order, when it is worthwhile) ↗ · Java SE 21 API: StampedLock (optimistic reads, validate, not reentrant, no ownership) ↗ · Java SE 21 API: AbstractQueuedSynchronizer (int state, FIFO wait queue, barging) ↗ · Java SE 21 API: Thread.State (BLOCKED is for monitors, WAITING for LockSupport.park) ↗ · JDK 21 tool reference: jcmd (Thread.print -l prints java.util.concurrent locks) ↗ · JDK 21 tool reference: jfr (print, summary, view) ↗ · Java SE 21 Core Libraries: Virtual Threads (pinning inside synchronized, ReentrantLock for long I/O) ↗ · Report a problem