Workbench / Volume 3 Companion: The Backend
V3·38
Concurrency
Companion to Volume 3, chapter 38: how threads, the memory model, locks, virtual threads and structured concurrency connect; new angles (a lock as the one pen at a counter, happens-before as a signed handover slip, a virtual thread as a cook who steps away from a stove that's heating); what the chapter simplifies, measured on JDK 21 and the build's stage 39: a request deadline that never came because it was measured on a business clock a test had fixed, a deadlock the JVM's detector can't see when the threads are virtual, a stress test whose per-order checks passed while the queue under them was corrupt, and what a fair lock costs; the theory behind linearizability and progress guarantees; how ReentrantLock lets a thread barge; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 38 has six parts: foundations (concurrency against parallelism, the models), threads and tasks (threads, executors, futures), the memory model (why correct-looking code breaks, happens-before), synchronisation primitives (synchronized, volatile, atomics, explicit locks, coordinators, concurrent collections), modern Java concurrency (fork/join, thread-per-request against non-blocking, virtual threads, structured concurrency, async elsewhere, Go) and failure modes (deadlock, livelock and starvation, contention, false sharing, tools and testing).
The links worth remembering:
- Every correctness tool is a happens-before edge. A lock release and the next acquire, a
volatilewrite and a later read,Thread.start,join, a future's completion: each orders memory. Code without one of these between a write and a read has no guarantee the read sees it. - Virtual threads change the cost of waiting, not the rules of sharing. Blocking becomes cheap, so thread-per-request scales; shared mutable state needs the same locks, and some tools (pinning, deadlock detection) behave differently.
- Concurrency bugs are found by invariants, not outputs. A run that "looks right" proves little; checking the structure's own invariants under load, and making the test fail on purpose once, does.
Explain it differently
1. A lock is the one pen at a counter. Whoever holds the pen fills in the shared form; everyone else waits. A non-fair counter lets whoever is nearest grab the pen when it's put down, even if others have been waiting; a fair one hands it to the front of the queue, and the counter gets slower (Gaps 4).
2. Happens-before is a signed handover slip. The night cook writes the stock count and signs the slip (releases the lock, writes the volatile); the morning cook reads the slip before the count (acquires, reads). Without the slip, the morning cook may be looking at an old copy of the count on their own clipboard (a CPU cache, a register).
3. A virtual thread is a cook who steps away from a heating stove. A platform thread stands at the stove while the water boils; a virtual thread hangs a note on it and goes to chop onions, and any free cook (a carrier thread) can come back when it boils. Pinning is a cook who can't step away because they're holding the only pen.
4. A deadline must be measured with a stopwatch, not the wall clock. The wall clock can be wrong, set back by NTP, or deliberately frozen for a test. A stopwatch (System.nanoTime) only goes forward. Stage 39 found its request deadline using the wall clock (Gaps 1).
5. Deadlock is two cooks each holding one of the two pans the other needs. Neither will put theirs down. The fix is a rule: always pick up the smaller pan first. The JVM can spot this standoff among its regular cooks, but not among the ones who step away (Gaps 2).
6. A stress test is a fire drill. It only tells you something if you've once seen the alarm go off. Stage 39's drill was run once with a lock removed, to check that it would ring (Gaps 3).
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from OpenJDK 21.0.12 on a 2-core machine and the build's stage 39 (exp/39), unless stated.
1. "Inject a clock" and "timeouts must be monotonic" pull in opposite directions. The chapter's exercises recommend both: inject a Clock so tests control time, and use System.nanoTime for durations. TiffinBox did the first everywhere, including the deadline that stops a client trickling its request one byte at a time. A client sending a 62-byte head at one byte per 100 ms, against an 800 ms deadline:
system clock: 11 of 62 bytes in 1.1 s, cut off (SocketException)
fixed clock (a test): 62 of 62 bytes in 6.2 s, answered: HTTP/1.1 200 OK
clock stepped back 1 h: 62 of 62 bytes in 6.2 s, answered: HTTP/1.1 200 OK
With the business clock fixed (as stage 38's new test does) or stepped back by NTP, the deadline never arrived. A server in a test environment with a frozen clock could be held open by any slow client. Two kinds of time, two tools: a Clock for when (prices, promises, logs), nanoTime for how long (deadlines, timeouts, measurements). And compare nanoTime readings by subtraction, because the counter may start anywhere:
deadline = -9223372036854775409
at start, now > deadline: true (the naive check: already late)
at start, now - deadline > 0: false (subtraction: 500 ns early)
600 ns later, now - deadline > 0: true
2. The JVM's deadlock detector doesn't see virtual threads. The chapter says thread dumps "detect deadlocks automatically" and ThreadMXBean.findDeadlockedThreads() "does it programmatically". Two threads taking two locks in opposite orders, in separate JVMs:
platform threads, ReentrantLock: still running true/true, findDeadlockedThreads: 2 threads [Thread-0, Thread-1]
platform threads, synchronized : still running true/true, findDeadlockedThreads: 2 threads [Thread-0, Thread-1]
virtual threads, ReentrantLock: still running true/true, findDeadlockedThreads: null (none found)
virtual threads, synchronized : still running true/true, findDeadlockedThreads: null (none found)
jcmd <pid> Thread.print prints "Found one Java-level deadlock" for the platform threads and nothing for the virtual ones; the JSON dump (Thread.dump_to_file) lists virtual threads but has no deadlock analysis. TiffinBox's request handlers are virtual threads, so a deadlock there would show only as requests that never answer. Prevention (a lock order, tryLock with a timeout) matters more than detection; and a request timeout in a stress test is the detector you have.
3. A stress test that passes proves little until you've seen it fail. The chapter recommends stress tests. Stage 39's stress test (16 to 64 customers placing orders while 4 kitchen threads move them and a display follows the stream) found nothing on the real code:
1280 orders, 2692 moves, 0 refused (409), 0 server errors (500), 0 requests unanswered after 10 s
events out of lifecycle order: 0; display ends elsewhere than the server: 0; queue differs: 0 (open orders 436, queue size 436, queue consistent)
Was it able to find anything? With the lock around the (not thread-safe) kitchen queue removed:
1280 orders, 2689 moves, 0 refused (409), 0 server errors (500), 0 requests unanswered after 10 s
events out of lifecycle order: 0; display ends elsewhere than the server: 0; queue differs: 0 (open orders 426, queue size 427, queue INCONSISTENT)
1280 orders, 2672 moves, 0 refused (409), 1 server errors (500), 0 requests unanswered after 10 s
events out of lifecycle order: 0; display ends elsewhere than the server: 0; queue differs: 0 (open orders 441, queue size 441, queue INCONSISTENT)
(a fourth run did not finish within 150 s)
Look at "queue differs: 0": every order's ticket was right, because the lookup side of the queue is a HashMap that happened to survive. The TreeSet ordering the tickets by time was corrupt (one run's server log had NullPointerException: Cannot read field "left" because "r" is null, from inside a red-black tree), and one run hung, the classic sign of a cycle in a tree or list damaged by concurrent writes. Only the structure's own invariant (consistent()) caught every run. Check invariants, not just answers, and run the test once against a deliberately broken version.
4. Locks are unfair by default, and fairness is expensive. The chapter lists fairness as a reason to choose ReentrantLock, without numbers. Eight threads taking one lock for about 1 µs each, for 2 s:
non-fair 1,239,965 acquisitions; per thread 134,958 to 175,547; worst wait 31.9 ms
fair 146,586 acquisitions; per thread 17,794 to 21,032; worst wait 6.4 ms
And how often the thread that just released the lock took it straight back, with three others trying:
non-fair: 629,835 acquisitions, 99.4% by the thread that had just released it, with 3 other threads trying
fair: 92,341 acquisitions, 20.4% by the thread that had just released it, with 3 other threads trying
A non-fair lock lets the releasing thread barge back in (it's running, its caches are warm, no wake-up needed), which gives 8× the throughput here and a worse tail. Fair locks hand over strictly, paying a park and unpark per handover. Prefer short critical sections to fair locks; reach for fairness when a waiting thread must not starve (a writer behind a stream of readers).
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
"Inject a Clock for everything time-related." |
Business time from a Clock; deadlines from nanoTime. |
Gaps 1; stage 39 |
"nanoTime values can be compared with <." |
Compare differences; the counter can wrap. | Gaps 1 |
| "The JVM will tell me about a deadlock." | Not among virtual threads, on JDK 21. | Gaps 2 |
| "A stress test that passes means the code is safe." | Only if it can fail; check invariants. | Gaps 3 |
"ReentrantLock serves threads in order." |
Only new ReentrantLock(true), at a large cost. |
Gaps 4 |
| "Virtual threads remove the need for locks." | They change the cost of blocking, not data races. | the chapter's lab, Experiment 5 |
"cancel(true) stops a CompletableFuture's work." |
It doesn't interrupt the task. | Exercises P2 |
Theoretical gaps: the ideas behind the chapter
1. Linearizability. Herlihy and Wing (1990): a concurrent object is linearizable if every operation appears to take effect at a single instant between its call and return. It's the precise meaning of "thread-safe" for a data structure, and what tools like Lincheck and jcstress test. ConcurrentHashMap's single-key operations are linearizable; its size() and iterators aren't.
2. Progress guarantees. Blocking (a lock: if the holder stops, everyone waits), obstruction-free, lock-free (some thread always makes progress; CAS loops) and wait-free (every thread finishes in bounded steps). Deadlock is a failure of blocking progress; livelock of lock-free progress.
3. The Coffman conditions. Deadlock needs mutual exclusion, hold-and-wait, no preemption and a circular wait (Coffman et al., 1971). Breaking any one prevents it: lock ordering breaks the cycle; tryLock with a timeout adds preemption.
4. Monotonic and wall-clock time. POSIX distinguishes CLOCK_REALTIME (adjustable) from CLOCK_MONOTONIC; System.nanoTime is the latter, Instant.now the former. Distributed systems add logical clocks (Lamport, 1978), covered in Volume 4.
5. Data-race-free programs are sequentially consistent. The Java memory model's core guarantee (Manson, Pugh and Adve, 2005): if a program has no data races, every execution behaves as if operations ran in some interleaving. Races void that promise, which is why "it worked when I ran it" means nothing for racy code.
Applying it
Code walkthrough
Gaps 4 comes from how ReentrantLock decides who gets the lock. From openjdk/jdk21u, src/java.base/share/classes/java/util/concurrent/locks/ReentrantLock.java.
lock(): one try, then the queue
@ReservedStackAccess
final void lock() {
if (!initialTryLock())
acquire(1);
}
Both kinds of lock first call initialTryLock(); if it fails, acquire (in AbstractQueuedSynchronizer) enqueues the thread and parks it until it's woken at the head of the queue.
The non-fair try: grab it if it's free
final boolean initialTryLock() {
Thread current = Thread.currentThread();
if (compareAndSetState(0, 1)) { // first attempt is unguarded
setExclusiveOwnerThread(current);
return true;
} else if (getExclusiveOwnerThread() == current) {
int c = getState() + 1;
if (c < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(c);
return true;
} else
return false;
}
"First attempt is unguarded": a compare-and-swap from 0 to 1, without looking at the queue. A thread that just released the lock and loops back to lock() is still running, so it usually wins this race against a waiter that has to be unparked and scheduled first: 99.4% of acquisitions in Gaps 4. The second branch is reentrancy: the owner taking the lock again increments a count.
The fair try: only if nobody is waiting
final boolean initialTryLock() {
Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (!hasQueuedThreads() && compareAndSetState(0, 1)) {
setExclusiveOwnerThread(current);
return true;
}
} else if (getExclusiveOwnerThread() == current) {
if (++c < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(c);
return true;
}
return false;
}
protected final boolean tryAcquire(int acquires) {
if (getState() == 0 && !hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
One condition differs: !hasQueuedThreads() (and, in tryAcquire, !hasQueuedPredecessors()). If anyone is queued, the newcomer queues too, so every handover is a park and an unpark: the 8× in Gaps 4. tryLock() without arguments ignores fairness even on a fair lock (its documentation says so).
Debugging drills
D1. Requests that hang only in the staging environment
In staging, a few connections from a monitoring agent stay open for hours, and the server eventually refuses new ones (503). Production, with the same code and limits, is fine. Staging runs with a fixed Clock so that demo data looks like the same morning every day.
D2. All requests to one endpoint stop; the thread dump says nothing
After a release, POST /transfers requests hang until the client times out; other endpoints work. jcmd <pid> Thread.print shows no deadlock and no blocked platform threads. The server uses virtual threads per request.
D3. A stress test that has never failed
A team's CacheStressTest has passed on every build for two years. A production incident turns out to be a race in that cache.
D4. One customer's requests are much slower under load
Under load, the p99 latency of order placement is 40 ms, but one large customer's requests sometimes take 2 s. Placement takes a per-customer lock (ReentrantLock), and that customer's integration sends 50 parallel requests.
Career-oriented
Interview prep
Mid-level 1: two kinds of time
Question. "Implement a method that waits at most 2 seconds for a result. Which clock do you use, and why?"
How to get there. Wall-clock against monotonic, then the comparison.
Mid-level 2: fixing a check-then-act
Question. "if (!map.containsKey(k)) map.put(k, load(k)); on a ConcurrentHashMap loads some keys twice. Fix it, and say what your fix costs."
How to get there. Atomic operations, then what runs under the bin lock.
Senior 1: proving a concurrent component correct enough
Question. "You've written an in-memory order book used by many threads. How do you convince yourself and reviewers it's correct?"
How to get there. Design, invariants, tests that can fail, tools.
Senior 2: moving a service to virtual threads
Question. "We're moving a Tomcat service to virtual threads. What could go wrong, and what do you check?"
How to get there. Pinning, bounded resources, ThreadLocal, observability.
Staff 1: a concurrency standard for many teams
Question. "Concurrency bugs keep reaching production across our 40 services. What standard and tooling do you introduce?"
How to get there. Default designs, banned patterns, tests, runtime signals.
Staff 2: lock contention in a hot path
Question. "Profiling shows 30% of CPU in lock contention on a pricing cache under peak load. What's the study plan?"
How to get there. Measure, shrink, split, remove.