BE·38
Concurrency
Running work at the same time, correctly. Covers threads and executors, futures and CompletableFuture, synchronized and volatile, the Java Memory Model and happens-before, atomics and CAS, locks (ReentrantLock, ReadWriteLock, StampedLock), semaphores, latches and barriers, ForkJoinPool, virtual threads and structured concurrency, then deadlock, starvation, contention and false sharing. Compared with goroutines and channels, Rust's Send/Sync and async, C++ atomics and memory orders, C pthreads, Zig, C# async/await, Kotlin coroutines, Python's GIL, and Erlang actors.
Start here: doing several things at once
Why backends are concurrent
A backend serves many users at the same moment, and most of each request is waiting: for the database, another service, a file. Concurrency means structuring a program as several tasks in progress at once, so one task's waiting doesn't hold up the others. Parallelism means actually running on several CPU cores at the same instant. A web server needs concurrency even on one core; a number-crunching job needs parallelism to use all eight. Chapter 2 of Volume 1 covered processes and threads; this chapter is about using them correctly in Java, with comparisons to Go, Rust, C#, Kotlin, Erlang and JavaScript.
A thread is an independent path of execution inside a process, with its own call stack, sharing the process's memory (the heap) with every other thread. That sharing is what makes threads useful and dangerous.
The danger: shared, changing data
Two threads each add one to a counter a million times. Three versions:
static int unsafeCount = 0; // a plain field
static int lockedCount = 0; static final Object lock = new Object();
static AtomicInteger atomicCount = new AtomicInteger();
() -> { for (int i = 0; i < 1_000_000; i++) unsafeCount++; }
() -> { for (int i = 0; i < 1_000_000; i++) synchronized (lock) { lockedCount++; } }
() -> { for (int i = 0; i < 1_000_000; i++) atomicCount.incrementAndGet(); }
2 threads × 1,000,000 increments: plain int 1,949,966 | synchronized 2,000,000 | AtomicInteger 2,000,000
count++ looks like one step but is three: read the value, add one, write it back. When two threads interleave those steps, both read 41 and both write 42, and an increment vanishes: a race condition (here about 50,000 were lost, and the number changes every run). Two fixes:
synchronized(a lock): only one thread at a time can be inside a block guarded by the same lock object, so the read-add-write can't interleave. Java'sReentrantLockdoes the same with more options.- Atomic variables (
AtomicInteger,AtomicLong,LongAdder): the hardware does the read-modify-write as one indivisible instruction (compare-and-swap), with no lock.
The best fix is often to not share mutable state at all: give each task its own data and combine results at the end, or pass immutable messages between tasks. Locks also make the other thread see the latest value, which a plain field doesn't guarantee (the lab shows a loop that never notices a flag change); that's the memory model, covered in full depth below.
The payoff: waiting at the same time
Three calls that each wait 300 ms, done one after another and then at the same time:
String m = fetch("menu", 300), s = fetch("stock", 300), o = fetch("offers", 300);
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
Future<String> fm = ex.submit(() -> fetch("menu", 300));
Future<String> fs = ex.submit(() -> fetch("stock", 300));
Future<String> fo = ex.submit(() -> fetch("offers", 300));
List.of(fm.get(), fs.get(), fo.get());
}
one after another: 919 ms
concurrently on virtual threads: [menu, stock, offers] in 313 ms
An ExecutorService runs tasks on threads for you; submit returns a Future, a handle to a result that will arrive later, and get() waits for it. Since JDK 21, virtual threads are cheap threads managed by the JVM rather than the operating system: you can have millions, so the simple rule for I/O-bound backend work is "one virtual thread per task, and write ordinary blocking code". The try (…) block waits for all tasks before closing.
Composing results without blocking
CompletableFuture<String> page = CompletableFuture.supplyAsync(() -> fetch("menu", 300))
.thenCombine(CompletableFuture.supplyAsync(() -> fetch("stock", 300)), (menu, stock) -> menu + "+" + stock)
.thenApply(String::toUpperCase)
.completeOnTimeout("FALLBACK", 1, TimeUnit.SECONDS);
CompletableFuture: MENU+STOCK in 307 ms
CompletableFuture is Java's promise: you describe what to do when results arrive (combine two, transform, fall back after a timeout), similar to JavaScript's Promise, C#'s Task and Kotlin's coroutines. It was the main tool for non-blocking backends before virtual threads, and remains useful for fan-out with timeouts; structured concurrency (in preview, full depth below) is the newer, simpler way to run related subtasks together.
Shared state done safely
Map<String, Integer> views = new ConcurrentHashMap<>();
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) { String dish = i % 2 == 0 ? "dosa" : "idli"; ex.submit(() -> views.merge(dish, 1, Integer::sum)); }
}
10,000 virtual threads counting views: {dosa=5000, idli=5000}
Use the concurrent collections (ConcurrentHashMap, BlockingQueue, CopyOnWriteArrayList) for shared data, and their atomic compound operations (merge, compute, computeIfAbsent) rather than "check, then act" in two steps, which races just like count++ (lab experiment 5).
Four ways it goes wrong
- Race condition: the result depends on timing (lost updates, check-then-act).
- Visibility: one thread never sees another's write (missing
volatileor lock). - Deadlock: two threads each hold a lock the other needs, and wait forever (lab experiment 2).
- Starvation and exhaustion: too few threads for blocking work, or unbounded queues filling memory.
These bugs are non-deterministic: they pass tests and appear under production load. The defences are design (immutability, confinement, message passing), the right library tools, and stress tests plus tools like thread dumps (jcmd <pid> Thread.print), which detect deadlocks automatically.
How deep to go in concurrency
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain threads, races, locks and why shared mutable state is dangerous |
| L2 | Use executors, virtual threads, futures, atomics and concurrent collections correctly |
| L3 | Explain the Java memory model (happens-before, volatile, safe publication), lock implementations, fork-join, structured concurrency, and Go, Rust, Erlang and async/await models |
| L4 | Diagnose races, visibility bugs, deadlocks, pinning and pool exhaustion from thread dumps and stress tests |
| L5 | Design concurrency for a service: pool sizing, backpressure, timeouts, cancellation |
| L6 | Set concurrency standards and review practices for a codebase; choose models per system |
Foundations
Concurrency versus parallelism
- Concurrency is about structure: several tasks are in progress during overlapping time periods, interleaved or simultaneous. A web server handling 10,000 connections is concurrent even on one core.
- Parallelism is about execution: several computations literally run at the same instant on multiple cores.
Rob Pike's phrasing: "Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once." Backend services are mostly concurrent and I/O-bound (waiting on databases and networks). Batch jobs and data processing are often parallel and CPU-bound. The right tools differ for the two cases.
Vol. 1 ch. 8 covers the OS view: processes, kernel threads, context switches, scheduling and the hardware memory hierarchy. This chapter builds on it.
Concurrency models compared
| Model | Idea | Where |
|---|---|---|
| Shared memory + locks | Threads share the heap; coordinate with mutexes, conditions and atomics | Java, C#, C/C++, Rust, Go (also available), Zig |
| Message passing (CSP) | Independent processes communicate over channels; "share memory by communicating" | Go (goroutines + channels), Rust (mpsc, crossbeam), Kotlin Channel, Clojure core.async |
| Actors | Each actor owns private state and a mailbox, and processes one message at a time | Erlang/Elixir (BEAM processes), Akka/Pekko (JVM), Orleans (.NET) |
| Async/await (cooperative tasks on an event loop or executor) | Functions suspend at await points instead of blocking threads |
JS/Node, Python asyncio, C#, Rust (Tokio), Kotlin coroutines, Swift, C++20 coroutines |
| Reactive streams | Asynchronous pipelines with backpressure | Reactor/RxJava (chapter 48), Akka Streams |
| Data parallelism | Split data, process chunks in parallel, combine | Java parallel streams, ForkJoin, Rayon, OpenMP, PLINQ |
| Software transactional memory | Memory transactions that retry on conflict | Haskell STM, Clojure refs |
Java supports most of these. Its historical default is shared memory with platform threads, and its modern default for servers is virtual threads, which let simple blocking code scale like async code.
Threads and tasks
Threads, Runnable and Callable
A java.lang.Thread (a platform thread) wraps one OS thread: about 1 MB of reserved stack by default, a kernel scheduler entry, and creation that costs tens of microseconds. Work is described by:
Runnable:void run(), with no result and no checked exceptions.Callable<V>:V call() throws Exception, which returns a result and can throw.
Thread t = Thread.ofPlatform().name("worker-", 0).start(() -> doWork()); // JDK 21 builder
t.join(); // wait for completion (InterruptedException)
// Don't manage raw threads in application code: use executors.
Interruption is Java's cooperative cancellation. t.interrupt() sets a flag. Blocking methods (sleep, wait, join, BlockingQueue.take, many I/O operations on interruptible channels) throw InterruptedException and clear the flag. Long CPU loops must check Thread.currentThread().isInterrupted(). The cardinal rule: never swallow InterruptedException. Either propagate it, or restore the flag with Thread.currentThread().interrupt() before returning, so code further up the stack knows a cancellation was requested.
try {
queue.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the flag
return; // and stop what you're doing
}
Executors and ExecutorService
An executor separates submitting a task from how and where it runs. ExecutorService adds lifecycle management and futures.
ExecutorService pool = Executors.newFixedThreadPool(8); // 8 platform threads + an unbounded queue
Future<Report> f = pool.submit(() -> buildReport(id)); // Callable → Future
Report r = f.get(2, TimeUnit.SECONDS); // blocks; throws TimeoutException / ExecutionException
pool.shutdown(); // no new tasks; finish queued ones
if (!pool.awaitTermination(30, TimeUnit.SECONDS)) pool.shutdownNow(); // interrupt running tasks
// JDK 19+: ExecutorService is AutoCloseable; close() = shutdown + await termination
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
exec.submit(() -> sendEmail(a));
exec.submit(() -> sendEmail(b));
} // waits for both
The factory methods hide important choices. ThreadPoolExecutor exposes them:
var pool = new ThreadPoolExecutor(
8, // corePoolSize: threads kept alive
32, // maximumPoolSize: used ONLY when the queue is full
60, TimeUnit.SECONDS, // keep-alive for threads above core
new ArrayBlockingQueue<>(1_000), // BOUNDED queue: backpressure instead of OOM
Thread.ofPlatform().name("report-", 0).factory(),
new ThreadPoolExecutor.CallerRunsPolicy()); // when saturated: run in the caller (natural throttling)
Pitfalls of the convenience factories:
newFixedThreadPool/newSingleThreadExecutoruse an unboundedLinkedBlockingQueue. Under overload, tasks pile up untilOutOfMemoryError, and latency grows without bound.newCachedThreadPoolcreates unbounded threads. A burst can create thousands of platform threads and exhaust memory or the OS thread limit.- With an unbounded queue,
maximumPoolSizenever takes effect, because new threads are added only when the queue rejects a task. - Sizing: for CPU-bound work, about the number of cores. For I/O-bound work on platform threads, cores × (1 + wait time / compute time), which is why pools of 200 threads were normal for blocking servers. With virtual threads, you stop sizing pools for I/O altogether.
- Rejection policies:
AbortPolicy(throw, the default),CallerRunsPolicy,DiscardPolicyandDiscardOldestPolicy. Choose deliberately; this is load shedding (chapter 52). - Exceptions in
execute()d tasks go to the thread's uncaught exception handler. Insubmit()ted tasks they're captured in the Future and silently lost if nobody callsget(). ScheduledExecutorService.scheduleAtFixedRate: if a run throws, all future runs are silently cancelled. Catch everything inside scheduled tasks.
Future and CompletableFuture
Future<V> represents a pending result, but its only way to get the value is a blocking get(). CompletableFuture<V> (Java 8) adds composition (callbacks that run when the value is ready) and explicit completion:
ExecutorService io = Executors.newVirtualThreadPerTaskExecutor();
CompletableFuture<Customer> customer = CompletableFuture.supplyAsync(() -> customers.find(id), io);
CompletableFuture<List<Order>> orders = CompletableFuture.supplyAsync(() -> orderClient.forCustomer(id), io);
CompletableFuture<Profile> profile = customer
.thenCombine(orders, Profile::new) // both results → combine
.thenCompose(p -> CompletableFuture.supplyAsync(() -> enrich(p), io)) // async step returning a CF (flatMap)
.thenApply(this::redact) // sync transform (map)
.orTimeout(2, TimeUnit.SECONDS) // JDK 9: completes exceptionally on timeout
.exceptionally(ex -> Profile.fallback(id)); // recover
CompletableFuture<Void> all = CompletableFuture.allOf(f1, f2, f3); // wait for all (then join each)
CompletableFuture<Object> any = CompletableFuture.anyOf(f1, f2); // first to complete
| Method | Shape | Analogy |
|---|---|---|
thenApply(fn) |
T → U |
map |
thenCompose(fn) |
T → CompletableFuture<U> |
flatMap (chapter 37) |
thenCombine(other, bifn) |
Join two independent futures | zip |
thenAccept / thenRun |
Consume / side effect | forEach |
exceptionally / handle / whenComplete |
Recover / see both outcomes / observe | catch / finally |
…Async variants |
Run the callback on an executor instead of the completing thread | — |
Pitfalls:
- Default executor:
supplyAsync(supplier)without an executor uses the common ForkJoinPool, sized for CPU work. Blocking calls in it starve the whole JVM's default async work. Always pass an executor for I/O. - Which thread runs callbacks? Non-async
thenApplyruns on whichever thread completes the future, or immediately on the caller's thread if it's already complete. Heavy work there can stall unexpected threads, such as an HTTP client's I/O thread. - Cancellation doesn't interrupt:
cf.cancel(true)marks the future cancelled but doesn't interrupt the running supplier. Work keeps running and nothing cancels dependent futures' work either. - Lost exceptions: a chain without
exceptionally/handle/joinswallows failures silently. - Wrapping: exceptions arrive wrapped in
CompletionException(orExecutionExceptionfromget()). UnwrapgetCause(). - Context:
ThreadLocalvalues (MDC, security context, transactions) don't follow callbacks to other threads.
With virtual threads, much of this complexity becomes unnecessary: you write sequential blocking code and fork concurrency where needed with structured concurrency (below). CompletableFuture remains useful for integrating callback-based APIs.
The memory model
Why correct-looking code breaks
Two threads, no synchronisation:
class Flag {
boolean ready = false; // not volatile
int value = 0;
void writer() { value = 42; ready = true; }
void reader() { while (!ready) { } System.out.println(value); }
}
This can loop forever (the JIT hoists the read of ready out of the loop, since nothing in this thread changes it) or print 0 (the writes are reordered by the compiler or CPU, so ready = true becomes visible before value = 42). Three mechanisms cause this (Vol. 1 ch. 7–8):
- Compiler reordering and caching: javac, the JIT, and C/C++/Rust compilers reorder and eliminate memory accesses that look independent within one thread.
- CPU store buffers and caches: a core's writes sit in its store buffer before reaching the coherent cache, and other cores can observe them in a different order. x86 is fairly strong (TSO: only store→load reordering is visible). ARM and POWER are weak and reorder much more, so code that "works on my x86 laptop" can fail on Graviton or Apple Silicon.
- Non-atomic operations:
count++is load, add, store. Two threads interleave, and increments are lost. On the JVM, non-volatilelonganddoublewrites may even tear into two 32-bit halves (permitted by the spec, though not done by 64-bit HotSpot).
A memory model is the contract that says which values a read may observe. Java's (the JMM, JSR-133, Java 5) was the first rigorous one for a mainstream language. C++11 and C11 followed with a model that Rust and Zig also adopted, and Go published its own in 2022.
Happens-before
The JMM defines a partial order called happens-before (HB). If action A happens-before action B, then A's effects are visible to B and A appears ordered before B. Without an HB edge between a write and a read of the same variable from different threads, you have a data race, and the read can see stale or reordered values.
HB edges come from:
| Rule | Edge |
|---|---|
| Program order | Each action in a thread HB every later action in that thread |
| Monitor lock | Unlocking a monitor HB every subsequent lock of the same monitor |
| Volatile | A write to a volatile field HB every subsequent read of that field |
| Thread start | t.start() HB every action in t |
| Thread termination | Every action in t HB another thread's return from t.join() (or seeing isAlive() false) |
| Interruption | t.interrupt() HB t detecting the interrupt |
| Final fields | The end of a constructor HB any read of final fields through a reference obtained after construction (if this didn't escape) |
| Library guarantees | BlockingQueue.put HB take of that element; Future completion HB get() returning; executor submit HB the task running; CountDownLatch.countDown HB await returning; ConcurrentHashMap.put HB a subsequent get of that key |
| Transitivity | If A HB B and B HB C, then A HB C |
The rule to internalise: every piece of shared mutable state must be accessed under a consistent happens-before discipline. That means guarded by the same lock, published through a volatile field or atomic, handed off through a concurrent collection or queue, or made immutable and safely published.
Safe publication means making an object visible to other threads with an HB edge, through a volatile/final field, a lock, a concurrent collection, or static initialisation. Unsafely published objects can be seen half-constructed. Double-checked locking without volatile was the infamous broken idiom:
// BROKEN without volatile: another thread can see a non-null 'instance' whose fields aren't initialised yet
class Config {
private static volatile Config instance; // volatile makes it correct (Java 5+)
static Config get() {
Config c = instance;
if (c == null) {
synchronized (Config.class) {
c = instance;
if (c == null) instance = c = new Config();
}
}
return c;
}
}
// Simpler and always safe: the holder idiom. Class initialisation is lazy and thread-safe by the JLS.
class Config2 {
private static final class Holder { static final Config2 INSTANCE = new Config2(); }
static Config2 get() { return Holder.INSTANCE; }
}
Memory models in other languages
| Language | Model | Data races |
|---|---|---|
| Java | JMM: happens-before. Racy programs still have some defined semantics (no out-of-thin-air values, no crashes) | Bugs, but memory-safe |
| C / C++ | C11/C++11: atomics with explicit memory orders | Undefined behaviour for non-atomic racing accesses |
| Rust | C++20's atomics model | Impossible in safe Rust: the type system (Send/Sync and borrowing) forbids unsynchronised shared mutation at compile time. Only unsafe can create them |
| Go | Go memory model (2022 revision): DRF-SC (data-race-free programs behave sequentially consistently). Channels, mutexes and sync/atomic create HB edges |
Bugs. Races on multi-word values (interfaces, slices, strings) can corrupt memory and crash. go test -race detects them dynamically |
| C# | ECMA CLI model plus .NET's stronger practical guarantees; volatile, Volatile.Read/Write, Interlocked |
Bugs, memory-safe |
| Zig | C/C++-style atomics (@atomicLoad, @atomicStore, @cmpxchgStrong with orders) |
Undefined (like C) |
| Python | The GIL made most single operations effectively atomic. Free-threaded builds (3.13 experimental, officially supported since 3.14) keep core built-in types internally locked | Logical races still happen |
| Erlang/Elixir | No shared memory between processes | None by construction |
C++ and Rust expose memory orderings directly, which Java hides behind volatile, locks and VarHandle access modes:
| Ordering | Guarantee | Java analogue |
|---|---|---|
Relaxed |
Atomicity only, with no ordering of other accesses | VarHandle.getOpaque/setOpaque (roughly), LongAdder internals |
Release (store) / Acquire (load) |
Writes before the release are visible after an acquire that reads the released value: a one-way publication fence | VarHandle.setRelease/getAcquire, and the publication semantics of volatile |
AcqRel |
Both, for read-modify-write operations | compareAndSet |
SeqCst |
A single total order for all such operations | Java volatile (volatile accesses are sequentially consistent) |
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
static VALUE: AtomicU64 = AtomicU64::new(0);
static READY: AtomicBool = AtomicBool::new(false);
fn writer() { VALUE.store(42, Ordering::Relaxed); READY.store(true, Ordering::Release); }
fn reader() {
while !READY.load(Ordering::Acquire) { std::hint::spin_loop(); }
assert_eq!(VALUE.load(Ordering::Relaxed), 42); // guaranteed by the release/acquire pair
}
Synchronisation primitives
synchronized and intrinsic locks
Every Java object has an intrinsic lock (monitor). synchronized provides mutual exclusion (only one thread inside at a time) and visibility (the HB edges above):
public class Inventory {
private final Map<String, Integer> stock = new HashMap<>(); // guarded by 'this'
public synchronized boolean reserve(String sku, int qty) { // check-then-act made atomic
int have = stock.getOrDefault(sku, 0);
if (have < qty) return false;
stock.put(sku, have - qty);
return true;
}
public synchronized int available(String sku) { return stock.getOrDefault(sku, 0); } // reads need the lock too
}
Properties:
- Reentrant: a thread holding a lock can acquire it again (calling another
synchronizedmethod of the same object). - Block-structured: released automatically at the end of the block, even if an exception is thrown.
- Not interruptible, and there's no timeout or
tryLock. - Lock on a private final object, not
thisor a class literal, if outside code shouldn't be able to interfere:private final Object lock = new Object();. wait/notify/notifyAll(condition waiting on the monitor) must be called while holding the lock, always in awhileloop (spurious wakeups). Prefer higher-level utilities.- Virtual threads: before JDK 24, blocking inside
synchronizedpinned the virtual thread to its carrier (below). JEP 491 (JDK 24) removed most pinning, sosynchronizedis fine again on JDK 24+.
volatile
volatile on a field guarantees visibility and ordering (HB edges) and atomic reads and writes of the field itself, including long and double. It does not make compound operations atomic:
private volatile boolean running = true; // GOOD: a stop flag written by one thread, read by another
public void stop() { running = false; }
public void loop() { while (running) step(); }
private volatile int count;
public void inc() { count++; } // BROKEN: read-modify-write is not atomic; use AtomicInteger
Use volatile for flags, for publishing immutable snapshots (volatile Config current; that's replaced as a whole), and in lock-free algorithms combined with CAS.
Atomics and compare-and-swap
The java.util.concurrent.atomic package provides lock-free single-variable operations built on the CPU's compare-and-swap (LOCK CMPXCHG on x86, LL/SC or LSE CAS on ARM). The semantics of CAS: "if the current value equals expected, set it to new and return true, all atomically; otherwise return false".
AtomicLong seq = new AtomicLong();
long id = seq.incrementAndGet(); // atomic ++
AtomicReference<Config> cfg = new AtomicReference<>(initial);
cfg.updateAndGet(c -> c.withTimeout(Duration.ofSeconds(5))); // CAS retry loop inside; fn must be side-effect free
// The CAS loop pattern by hand
long prev, next;
do {
prev = max.get();
next = Math.max(prev, sample);
} while (!max.compareAndSet(prev, next));
// High contention counters: LongAdder stripes the value across cells, summing on read
LongAdder requests = new LongAdder();
requests.increment();
long total = requests.sum(); // not an atomic snapshot, but fine for metrics
- ABA problem: a value changes A→B→A between your read and your CAS, so the CAS succeeds even though state changed. This matters for lock-free stacks and pointer reuse.
AtomicStampedReferenceadds a version stamp. GC languages largely avoid the memory-reuse variant of ABA, while C, C++ and Rust need hazard pointers or epoch reclamation (crossbeam-epoch). VarHandle(JDK 9) gives atomic and fenced access to ordinary fields and array elements with explicit access modes (plain, opaque, acquire/release, volatile). The JDK's own concurrent classes use it (it replacedsun.misc.Unsafefor this purpose).- Contention: under heavy contention, CAS loops spin and retry, burning CPU.
LongAdderandStriped64spread the hot spot across cells.
Equivalents: std::atomic<T> in C++, std::sync::atomic::* in Rust, sync/atomic in Go (atomic.Int64 types since 1.19), Interlocked in C#, Zig's std.atomic.Value(T), and C11's <stdatomic.h>.
Explicit locks
java.util.concurrent.locks offers locks with more features than synchronized:
private final ReentrantLock lock = new ReentrantLock(); // optionally new ReentrantLock(true) for fairness
private final Condition notEmpty = lock.newCondition();
public void put(Job j) {
lock.lock();
try { // ALWAYS unlock in finally: nothing does it for you
queue.add(j);
notEmpty.signal();
} finally {
lock.unlock();
}
}
public Job take(Duration timeout) throws InterruptedException {
if (!lock.tryLock(timeout.toMillis(), TimeUnit.MILLISECONDS)) throw new TimeoutException(); // timed acquisition
try {
while (queue.isEmpty()) {
if (!notEmpty.await(timeout.toMillis(), TimeUnit.MILLISECONDS)) return null; // multiple conditions per lock
}
return queue.poll();
} finally {
lock.unlock();
}
}
| Lock | Use when |
|---|---|
synchronized |
Default. Simple mutual exclusion, fine with virtual threads on JDK 24+ |
ReentrantLock |
You need tryLock, timeouts, interruptible locking (lockInterruptibly), fairness, or several Conditions |
ReentrantReadWriteLock |
Many readers, rare writers, and long read critical sections. Readers share; writers are exclusive. Its overhead makes it slower than a plain lock for short sections |
StampedLock (JDK 8) |
Read-mostly data with very short reads: optimistic reads take no lock and validate afterwards. Not reentrant, no conditions, easy to misuse |
// StampedLock optimistic read: no lock acquired on the happy path
private final StampedLock sl = new StampedLock();
private double x, y;
double distanceFromOrigin() {
long stamp = sl.tryOptimisticRead(); // a version stamp, not a lock
double cx = x, cy = y; // may read inconsistent values…
if (!sl.validate(stamp)) { // …so check whether a write happened meanwhile
stamp = sl.readLock(); // fall back to a real read lock
try { cx = x; cy = y; } finally { sl.unlockRead(stamp); }
}
return Math.hypot(cx, cy);
}
Rust's design is instructive: Mutex<T> owns the data it protects. The only way to reach the T is through the guard returned by lock(), so you physically can't forget to lock, and the guard unlocks when dropped (RAII). Java's lock-and-data association is a comment ("guarded by lock"). Rust's is enforced by the type system.
use std::sync::{Arc, Mutex, RwLock};
let stock: Arc<Mutex<HashMap<String, u32>>> = Arc::new(Mutex::new(HashMap::new()));
fn reserve(stock: &Mutex<HashMap<String, u32>>, sku: &str, qty: u32) -> bool {
let mut guard = stock.lock().unwrap(); // unwrap: lock is 'poisoned' if a holder panicked
let have = guard.get(sku).copied().unwrap_or(0);
if have < qty { return false; }
guard.insert(sku.to_string(), have - qty);
true
} // guard dropped here: unlocked
// Arc<T>: atomically reference-counted shared ownership (like a GC'd reference)
// Send: safe to MOVE to another thread. Sync: safe to SHARE (&T) between threads.
// Rc<T> is !Send (non-atomic refcount), RefCell<T> is !Sync, so the compiler rejects sharing them across threads.
// Go: sync.Mutex is a separate value; convention places it above the fields it guards
type Inventory struct {
mu sync.Mutex
stock map[string]int // guarded by mu
}
func (inv *Inventory) Reserve(sku string, qty int) bool {
inv.mu.Lock()
defer inv.mu.Unlock() // defer guarantees unlock on every path (including panics)
if inv.stock[sku] < qty {
return false
}
inv.stock[sku] -= qty
return true
}
// Mutexes must not be copied after first use (go vet's copylocks check catches this): use pointer receivers.
// sync.RWMutex, sync.Once, sync.WaitGroup, sync.Cond, sync.Pool complete the toolbox.
#include <mutex>
#include <shared_mutex>
class Inventory {
mutable std::mutex mu_;
std::unordered_map<std::string, int> stock_; // guarded by mu_
public:
bool reserve(const std::string& sku, int qty) {
std::scoped_lock lock(mu_); // RAII; scoped_lock can lock several mutexes deadlock-free
auto& have = stock_[sku];
if (have < qty) return false;
have -= qty;
return true;
}
};
// std::shared_mutex + std::shared_lock for readers/writers; std::condition_variable for waiting.
// Clang's -Wthread-safety annotations (GUARDED_BY(mu_)) add Rust-like static checking.
#include <pthread.h>
static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
static int stock;
int reserve(int qty) {
pthread_mutex_lock(&mu);
int ok = stock >= qty;
if (ok) stock -= qty;
pthread_mutex_unlock(&mu); /* every early return must unlock: a classic source of bugs */
return ok;
}
const Inventory = struct {
mutex: std.Thread.Mutex = .{},
stock: std.StringHashMap(u32),
fn reserve(self: *Inventory, sku: []const u8, qty: u32) bool {
self.mutex.lock();
defer self.mutex.unlock();
const have = self.stock.get(sku) orelse 0;
if (have < qty) return false;
self.stock.put(sku, have - qty) catch return false;
return true;
}
};
private readonly Lock _lock = new(); // .NET 9 System.Threading.Lock (or lock on a private object)
public bool Reserve(string sku, int qty)
{
lock (_lock)
{
var have = _stock.GetValueOrDefault(sku);
if (have < qty) return false;
_stock[sku] = have - qty;
return true;
}
}
// Note: you can't 'await' inside lock { }; use SemaphoreSlim(1,1).WaitAsync() for async critical sections.
Semaphores, latches, barriers and phasers
Higher-level coordination utilities from java.util.concurrent:
| Utility | Purpose | Example |
|---|---|---|
Semaphore(n) |
At most n permits at once: bounding concurrency | Limit concurrent calls to a fragile downstream to 10, even with thousands of virtual threads |
CountDownLatch(n) |
One-shot: threads wait until n events have happened | Wait for 3 caches to warm before accepting traffic; start N workers simultaneously in a test |
CyclicBarrier(n) |
n threads wait for each other at a point, then all proceed. Reusable | Iterative simulations where each step needs all workers done |
Phaser |
A flexible, reusable barrier with dynamic party registration | Multi-phase work where participants join and leave |
Exchanger |
Two threads swap objects | Double-buffering |
// Bulkhead: cap concurrency to a dependency (chapter 52)
private final Semaphore paymentsPermits = new Semaphore(20);
public Receipt charge(Payment p) throws InterruptedException {
if (!paymentsPermits.tryAcquire(200, TimeUnit.MILLISECONDS)) throw new BulkheadFullException();
try {
return paymentsClient.charge(p);
} finally {
paymentsPermits.release();
}
}
// Latch: wait for N async initialisations
var ready = new CountDownLatch(3);
for (var cache : caches) exec.submit(() -> { cache.warm(); ready.countDown(); });
if (!ready.await(30, TimeUnit.SECONDS)) throw new IllegalStateException("warmup timed out");
Go equivalents: sync.WaitGroup (a latch), a buffered channel of size n as a semaphore, or golang.org/x/sync/semaphore. Rust: tokio::sync::Semaphore, std::sync::Barrier. C++20: std::counting_semaphore, std::latch, std::barrier.
Concurrent collections recap
Chapter 35 covered ConcurrentHashMap, CopyOnWriteArrayList, ConcurrentSkipListMap, ConcurrentLinkedQueue and the blocking queues. The key concurrency lessons:
- Prefer atomic compound methods (
computeIfAbsent,merge,putIfAbsent) to check-then-act sequences. - Use blocking queues for producer/consumer handoff. They provide the HB edge, the waiting and the backpressure (a bounded capacity).
- Immutable snapshots behind a volatile or atomic reference beat fine-grained locking for read-mostly configuration.
Modern Java concurrency
ForkJoinPool and work stealing
ForkJoinPool (JDK 7) runs divide-and-conquer tasks. Each worker thread has a double-ended queue of tasks. It pushes and pops its own tasks LIFO at one end (good cache locality), and when idle it steals FIFO from the other end of another worker's deque, taking older, typically larger tasks. That balances load with little contention.
class SumTask extends RecursiveTask<Long> {
private final long[] a; private final int lo, hi;
SumTask(long[] a, int lo, int hi) { this.a = a; this.lo = lo; this.hi = hi; }
@Override protected Long compute() {
if (hi - lo <= 10_000) { // sequential threshold
long s = 0; for (int i = lo; i < hi; i++) s += a[i]; return s;
}
int mid = (lo + hi) >>> 1;
var left = new SumTask(a, lo, mid);
left.fork(); // push to own deque (may be stolen)
long right = new SumTask(a, mid, hi).compute();// work on the other half directly
return right + left.join(); // join: may run other tasks while waiting
}
}
long total = ForkJoinPool.commonPool().invoke(new SumTask(data, 0, data.length));
The common pool backs parallel streams, CompletableFuture's default async methods, and (separately configured) the default scheduler for virtual threads. It's sized for CPU-bound work. Blocking in it is harmful unless you use ForkJoinPool.ManagedBlocker, which lets the pool add compensating threads.
The same design appears in Go's runtime scheduler (per-P run queues with stealing), Tokio's multi-threaded runtime, Rayon, .NET's thread pool, and Cilk (where it originated).
Thread-per-request versus non-blocking
How a server maps connections to threads determines its scalability (Vol. 1 ch. 8–9):
- Platform thread per request (classic Tomcat and Servlet, Spring MVC): simple sequential code with readable stack traces, but each blocked request holds an expensive OS thread. Throughput caps at pool size ÷ latency. For example, 200 threads with 100 ms per request is 2,000 requests per second, however idle the CPU is (Little's law, Vol. 6).
- Non-blocking event loop (Node.js, Netty, Spring WebFlux, Vert.x, nginx): a few threads multiplex thousands of connections using OS readiness APIs (epoll, kqueue, io_uring). It scales, but every operation must be non-blocking, code becomes callbacks, futures or reactive chains, stack traces lose meaning, and one accidental blocking call freezes everything on that loop.
- Lightweight threads (Go goroutines, Erlang processes, Java virtual threads): the runtime multiplexes many cheap user-mode threads over a few OS threads. When a lightweight thread blocks on I/O, the runtime parks it and runs another. You get thread-per-request code with event-loop scalability.
Virtual threads
Virtual threads (JDK 21, JEP 444, from Project Loom) are Thread instances implemented by the JVM rather than the OS:
- A virtual thread runs mounted on a carrier (platform) thread from a dedicated
ForkJoinPoolscheduler, by default with parallelism equal to the core count. - When it calls a blocking operation that the JDK has adapted (socket I/O,
Thread.sleep,BlockingQueue,ReentrantLock, JDBC drivers over sockets, andsynchronizedon JDK 24+), the JVM unmounts it: its stack frames are copied to the heap as a continuation object, and the carrier is free to run another virtual thread. When the I/O completes, the virtual thread is rescheduled, possibly on a different carrier. - Stacks are heap-allocated and grow as needed, starting at hundreds of bytes to a few KB. A million virtual threads is practical.
- Creation is cheap, so don't pool them. Create one per task:
Executors.newVirtualThreadPerTaskExecutor()orThread.ofVirtual().start(...).
// Spring Boot 3.2+: run request handling, @Async and scheduled tasks on virtual threads
// application.properties: spring.threads.virtual.enabled=true
// Plain Java: fan out 10,000 blocking HTTP calls with simple code
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<Price>> fs = skus.stream().map(s -> exec.submit(() -> priceClient.get(s))).toList();
for (var f : fs) prices.add(f.get());
}
What virtual threads don't change:
- CPU-bound work doesn't get faster. There are still only as many carriers as cores.
- Downstream limits still apply. Ten thousand concurrent virtual threads will happily open 10,000 database connections' worth of demand. The connection pool (HikariCP, chapter 49) becomes the bottleneck, and you need semaphores or bulkheads to protect dependencies.
- Pinning: a virtual thread that blocks while it can't unmount holds its carrier. That happens during native calls (JNI, FFM downcalls), and before JDK 24 inside
synchronized. Diagnose with JFR'sjdk.VirtualThreadPinnedevent. ThreadLocalstill works, but with a million threads, large thread-local caches (such as per-thread buffers orSimpleDateFormat) multiply memory. Scoped values (JEP 506, final in JDK 25) are the better tool for passing immutable context down a call tree.
// Scoped values: immutable, bounded lifetime, inherited by structured-concurrency child threads
static final ScopedValue<RequestContext> CTX = ScopedValue.newInstance();
ScopedValue.where(CTX, new RequestContext(userId, traceId)).run(() -> handle(request));
// deep inside: CTX.get().userId(): no parameter threading, no leaks after run() returns
Structured concurrency
Unstructured concurrency (executor.submit and forget) leaks work. If one of three parallel subtasks fails, the others keep running, nobody cancels them, and their threads and errors outlive the request. Structured concurrency applies the block structure of normal code to concurrent tasks: subtasks are forked inside a scope and can't outlive it. When the scope exits, all subtasks have finished; on failure the siblings are cancelled, and errors propagate to the parent.
// JDK 25+ API (StructuredTaskScope is a PREVIEW feature, seventh preview in JDK 27: --enable-preview)
Profile loadProfile(UserId id) throws InterruptedException {
try (var scope = StructuredTaskScope.open()) { // default joiner: all must succeed
Subtask<User> user = scope.fork(() -> users.find(id));
Subtask<List<Order>> orders = scope.fork(() -> orderClient.recent(id));
Subtask<Credit> credit = scope.fork(() -> creditClient.score(id));
scope.join(); // waits for all; if one fails, the others are cancelled (interrupted)
// and join throws StructuredTaskScope.FailedException wrapping the cause
return new Profile(user.get(), orders.get(), credit.get());
} // the scope can't close with running subtasks
}
// Other policies via Joiners: first success wins (hedged requests to replicas)
try (var scope = StructuredTaskScope.open(StructuredTaskScope.Joiner.<Price>anySuccessfulResultOrThrow())) {
replicas.forEach(r -> scope.fork(() -> r.price(sku)));
return scope.join(); // the first successful result; the rest are cancelled
}
Thread dumps (jcmd <pid> Thread.dump_to_file -format=json) show the scope tree, so you can see which request owns which subtasks. Structured concurrency originated in Martin Sústrik's and Nathaniel J. Smith's work (Python's Trio "nurseries") and is mainstream elsewhere:
// Kotlin coroutines: structured by default. coroutineScope waits for children and cancels siblings on failure.
suspend fun loadProfile(id: UserId): Profile = coroutineScope {
val user = async { users.find(id) }
val orders = async { orderClient.recent(id) }
val credit = async { creditClient.score(id) }
Profile(user.await(), orders.await(), credit.await())
}
// suspend functions compile to state machines (CPS); Dispatchers.IO for blocking calls
// Go: errgroup + context gives the same discipline (by convention, not enforced)
func LoadProfile(ctx context.Context, id string) (Profile, error) {
g, ctx := errgroup.WithContext(ctx) // ctx is cancelled when any goroutine returns an error
var u User
var os []Order
var c Credit
g.Go(func() (err error) { u, err = users.Find(ctx, id); return })
g.Go(func() (err error) { os, err = orders.Recent(ctx, id); return })
g.Go(func() (err error) { c, err = credit.Score(ctx, id); return })
if err := g.Wait(); err != nil {
return Profile{}, err
}
return Profile{u, os, c}, nil
}
// Cancellation is cooperative: callees must honour ctx.Done(). Every blocking API takes a ctx.
// Rust + Tokio: try_join! runs futures concurrently and short-circuits on the first error,
// DROPPING (cancelling) the other futures
async fn load_profile(id: UserId) -> Result<Profile, Error> {
let (user, orders, credit) = tokio::try_join!(
users.find(id),
order_client.recent(id),
credit_client.score(id),
)?;
Ok(Profile { user, orders, credit })
}
// tokio::task::JoinSet for dynamic fan-out; dropping a future cancels it at its next .await point.
// C#: Task.WhenAll + CancellationToken (cancellation is cooperative and explicit)
async Task<Profile> LoadProfile(UserId id, CancellationToken ct)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var user = users.FindAsync(id, cts.Token);
var orders = orderClient.RecentAsync(id, cts.Token);
var credit = creditClient.ScoreAsync(id, cts.Token);
try { await Task.WhenAll(user, orders, credit); }
catch { cts.Cancel(); throw; } // WhenAll doesn't cancel siblings by itself
return new Profile(user.Result, orders.Result, credit.Result);
}
# Python 3.11+: asyncio.TaskGroup is structured (cancels siblings, raises ExceptionGroup)
async def load_profile(id: str) -> Profile:
async with asyncio.TaskGroup() as tg:
user = tg.create_task(users.find(id))
orders = tg.create_task(order_client.recent(id))
credit = tg.create_task(credit_client.score(id))
return Profile(user.result(), orders.result(), credit.result())
# Elixir: Task.async + await, linked to the caller (a crash propagates); supervisors restart
def load_profile(id) do
tasks = [Task.async(fn -> Users.find(id) end),
Task.async(fn -> Orders.recent(id) end),
Task.async(fn -> Credit.score(id) end)]
[user, orders, credit] = Task.await_many(tasks, 2_000)
%Profile{user: user, orders: orders, credit: credit}
end
Blocking versus non-blocking, and async/await elsewhere
Most mainstream languages chose async/await (stackless coroutines) for scalable I/O. Java chose virtual threads (stackful continuations, transparent to code). The trade-offs:
Async/await (C#, Rust, JS, Python, Kotlin suspend, C++20 coroutines) |
Virtual threads / goroutines / BEAM processes (Java, Go, Erlang) | |
|---|---|---|
| Code style | async fn / await markers |
Ordinary blocking code |
| Function colouring | Yes: async functions can only be awaited from async functions; sync and async APIs split ecosystems | No colouring: any function can block |
| Suspension points | Explicit (await), so you know where interleaving can happen |
Implicit (any blocking call) |
| Memory per task | Very small (a state machine sized to the live variables) | Small (a growable stack) |
| Blocking a thread by accident | Stalls the executor (Tokio warns about blocking in async) | Fine (except pinning) |
| Cancellation | Rust: drop the future. C#/Kotlin: tokens and cooperative cancellation | Java: interruption. Go: context. Erlang: exit signals |
| Runtime | Rust: choose one (Tokio, async-std, smol, embassy). Others built in | Built into the language runtime |
Rust is worth singling out:
async fnreturns aFuture, a state machine that does nothing until polled (lazy, unlike JS promises).- An executor (Tokio) polls futures when the OS reports readiness (epoll, kqueue, IOCP, io_uring via tokio-uring).
Sendbounds decide whether a future can move between worker threads. Holding astd::sync::MutexGuardacross an.awaitmakes the future!Send, and the compiler catches it.tokio::task::spawn_blockingmoves blocking or CPU work off the async workers.
Zig removed its async/await keywords in 0.11. A new std.Io interface (in development through 2025–2026) reintroduces asynchrony as a library abstraction: the caller chooses blocking, thread-pool or event-loop I/O implementations without colouring functions.
C has no standard async model. Servers use epoll/kqueue directly or libraries (libuv under Node, libevent), with explicit state machines.
Python has the GIL (Global Interpreter Lock) in standard CPython: only one thread executes Python bytecode at a time, so threads help with I/O but not CPU-bound work (use multiprocessing or native extensions). The free-threaded build (PEP 703: experimental in 3.13, officially supported but optional in 3.14) removes the GIL, at some single-thread cost. asyncio provides async/await for I/O concurrency.
Erlang/Elixir: the BEAM VM runs millions of lightweight processes with preemptive scheduling (each process gets a budget of reductions), so a CPU-heavy process can't starve others. Processes share nothing and communicate by asynchronous messages. Supervisors restart failed processes. This "let it crash" fault-tolerance model is why WhatsApp and Discord-style systems run on it.
Go's goroutines and channels
Go deserves a closer look because it bakes concurrency into the language:
// Pipeline: generator → workers → collector, with cancellation and bounded concurrency
func Process(ctx context.Context, ids []string) ([]Result, error) {
jobs := make(chan string)
results := make(chan Result)
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { // producer
defer close(jobs) // closing signals "no more values" to range loops
for _, id := range ids {
select {
case jobs <- id: // unbuffered: blocks until a worker receives (synchronous handoff)
case <-ctx.Done():
return ctx.Err()
}
}
return nil
})
const workers = 8 // bounded parallelism
var wg sync.WaitGroup
for range workers {
wg.Add(1)
g.Go(func() error {
defer wg.Done()
for id := range jobs {
r, err := fetch(ctx, id)
if err != nil {
return err
}
select {
case results <- r:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
})
}
go func() { wg.Wait(); close(results) }() // close results once all workers finish
var out []Result
for r := range results {
out = append(out, r)
}
return out, g.Wait()
}
- Goroutines: start at about 2 KB of growable stack and are scheduled by the Go runtime's M:N scheduler (G goroutines, M OS threads, P logical processors =
GOMAXPROCS, with work stealing). Since Go 1.14, goroutines are asynchronously preempted with signals, so tight loops can't starve others. - Channels: typed conduits, unbuffered (synchronous rendezvous) or buffered (an asynchronous queue with capacity).
selectwaits on several channel operations at once. Sending on a closed channel panics; receiving from one yields the zero value immediately (v, ok := <-chtells you which). A nil channel blocks forever, which is useful for disabling aselectcase. - Goroutine leaks are the most common Go concurrency bug: a goroutine blocked forever on a channel nobody will read. Always give goroutines an exit path (
ctx.Done()).goleakdetects them in tests. - Go's own proverb is "Don't communicate by sharing memory; share memory by communicating". In practice, Go code uses
sync.Mutexplenty: channels for ownership transfer and orchestration, mutexes for protecting state.
Failure modes
Deadlock
A deadlock happens when threads wait for each other in a cycle, and none can proceed. The four Coffman conditions must all hold: mutual exclusion, hold-and-wait, no preemption, and circular wait. Break any one and deadlock is impossible. In practice you break circular wait with a global lock ordering:
// Deadlock: transfer(a, b) and transfer(b, a) concurrently. Each holds one lock and waits for the other.
void transfer(Account from, Account to, long amt) {
synchronized (from) { synchronized (to) { from.debit(amt); to.credit(amt); } }
}
// Fix: always lock in a consistent order (by a unique, comparable ID)
void transferSafe(Account a, Account b, long amt) {
Account first = a.id() < b.id() ? a : b, second = first == a ? b : a;
synchronized (first) { synchronized (second) { a.debit(amt); b.credit(amt); } }
}
// Or: tryLock with a timeout and back off (ReentrantLock), or avoid holding multiple locks at all.
Other deadlock sources:
- Calling alien code while holding a lock: listeners, callbacks or overridable methods that take other locks.
- Thread-pool starvation deadlock: a task in a bounded pool submits a subtask to the same pool and blocks waiting for it, while every thread is doing the same.
- Database deadlocks: two transactions locking rows in opposite orders. The database detects it and aborts one (Vol. 4).
- Go:
fatal error: all goroutines are asleep - deadlock!. The runtime detects global deadlocks, but not partial ones.
Detection: jstack <pid> or jcmd <pid> Thread.print prints "Found one Java-level deadlock" with the cycle. ThreadMXBean.findDeadlockedThreads() does it programmatically.
Livelock and starvation
- Livelock: threads keep reacting to each other without making progress, like two people stepping aside in a corridor in the same direction forever. Retry loops without randomised backoff cause it. Fix with jitter (chapter 52).
- Starvation: a thread never gets the resource it needs. Causes include unfair locks with barging, a priority inversion where a low-priority thread holds a lock a high-priority thread needs, long-running tasks hogging a small pool, or a writer starved by a continuous stream of readers on some read-write locks. Fair locks (
new ReentrantLock(true)) prevent barging at a throughput cost.
Contention
Contention happens when many threads compete for the same lock or cache line. Symptoms are high CPU in lock spinning or kernel futex calls, poor scaling as threads increase, and threads BLOCKED in dumps. Remedies, roughly in order:
- Don't share: confine state to one thread, or give each thread its own and merge later (
LongAdder, per-thread buffers, sharding by key). - Use immutable snapshots, published with a volatile reference.
- Shrink critical sections: compute outside the lock and do only the state change inside.
- Split locks: lock striping per bucket (as
ConcurrentHashMapdoes) or per entity. - Use read/write or optimistic schemes for read-mostly data.
- Use lock-free structures (CAS-based), with care.
Amdahl's law sets the ceiling: if 5% of the work is serialised (under a lock), the maximum speedup is 20× regardless of core count.
False sharing
CPUs keep caches coherent in units of cache lines (64 bytes on x86 and most ARM; 128 bytes on Apple M-series). If two threads write to different variables in the same cache line, the line bounces between cores (MESI invalidations, Vol. 1 ch. 7), even though there's no logical sharing. Throughput can drop by 10× or more.
// The JDK pads its own hot fields (Thread's random seeds, LongAdder cells, ForkJoinPool queues) with @Contended.
// Application code can't use @Contended without --add-exports, and it needs -XX:-RestrictContended.
// Manual padding works but relies on the JVM's field layout, which it may reorder.
class PaddedCounter {
long p1, p2, p3, p4, p5, p6, p7; // 56 bytes of padding before
volatile long value;
long q1, q2, q3, q4, q5, q6, q7; // and after
}
// Practical answer: LongAdder (already padded), or per-thread accumulation.
use crossbeam_utils::CachePadded;
struct Stats { hits: CachePadded<AtomicU64>, misses: CachePadded<AtomicU64> } // each on its own line
struct alignas(std::hardware_destructive_interference_size) Counter { std::atomic<long> v; };
Tools and testing
- Thread dumps (
jcmd <pid> Thread.print,jstack): look forBLOCKEDthreads and which monitor they wait on. JSON dumps (Thread.dump_to_file) include virtual threads. - JFR events (chapter 41):
jdk.JavaMonitorEnter(contended locks),jdk.ThreadPark,jdk.VirtualThreadPinned. - jcstress (OpenJDK): a harness that runs racy snippets billions of times to observe JMM outcomes. It's how JDK engineers test concurrency.
- Static analysis: Error Prone and SpotBugs (
@GuardedBy), and Clang's thread-safety analysis. - Dynamic race detectors: Go's
-raceand ThreadSanitizer for C, C++, Rust and Zig (-fsanitize=thread). There's no production-grade equivalent for Java; jcstress and careful design fill the gap. - Model checkers: loom for Rust explores thread interleavings exhaustively for small tests. TLA+ is for designs (Vol. 5).
- Testing tips: inject executors and clocks, use latches to force interleavings, and assert with timeouts (Awaitility, chapter 54). Never use
Thread.sleepfor synchronisation in tests.
Choosing a concurrency approach for a Java backend
- Default: synchronous blocking code on virtual threads (Spring Boot:
spring.threads.virtual.enabled=true). Limit downstream concurrency with connection pools and semaphores. - Fan-out within a request: structured concurrency (preview), or
CompletableFuturewith a virtual-thread executor. - Shared state: avoid it (stateless services, state in the database or cache). Otherwise use immutable snapshots,
ConcurrentHashMapatomic methods, orsynchronizedaround small sections. - CPU-bound batch work: a bounded platform-thread pool sized to cores, ForkJoin, or parallel streams outside request paths.
- Streaming with backpressure, or an existing reactive stack: WebFlux and Reactor (chapter 48).
- Async work that must survive crashes: not threads at all, but a durable queue (chapter 51).
Lab: five concurrency failures, reproduced
Compiled with JDK 21 (javac --release 21) and run on a 2-core machine; experiment 4 runs the same class on JDK 21 and JDK 25. Every bug here passes a casual test and appears under load.
Experiment 1: a write nobody sees
static boolean stop = false; // plain field
static volatile boolean vstop = false; // volatile field
new Thread(() -> { long n = 0; while (!stop) n++; }).start();
new Thread(() -> { long n = 0; while (!vstop) n++; }).start();
sleep(200); stop = true; vstop = true;
flag set to true; 2 s later: plain-boolean loop still running? true | volatile loop still running? false
The plain loop never stopped. Nothing in the Java memory model requires one thread's write to a plain field to become visible to another, so the JIT compiler legally hoisted the read of stop out of the loop (if (!stop) while (true) n++). volatile creates a happens-before edge: a write to a volatile field is visible to every later read of it. Locks, atomics, Thread.start/join, concurrent collections and executors give the same guarantee. Shutdown flags, "initialised" flags and lazily cached values are the usual victims; in Go the same bug exists (use sync/atomic or channels), and Rust rejects it at compile time.
Experiment 2: a deadlock, detected
Thread t1 = new Thread(() -> { synchronized (accountA) { sleep(50); synchronized (accountB) {} } }, "transfer A→B");
Thread t2 = new Thread(() -> { synchronized (accountB) { sleep(50); synchronized (accountA) {} } }, "transfer B→A");
long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
deadlocked threads found by ThreadMXBean: [transfer A→B waits for a lock held by transfer B→A] [transfer B→A waits for a lock held by transfer A→B]
Two transfers between the same accounts in opposite directions each took their first lock and waited forever for the second. The JVM can find such cycles: findDeadlockedThreads here, and jcmd <pid> Thread.print or jstack print "Found one Java-level deadlock" with both stacks. The fix is a global lock order (always lock the account with the smaller id first), tryLock with a timeout, or avoiding nested locks entirely (a single database transaction with row locks, which the database will detect and abort; Volume 4).
Experiment 3: blocking work on virtual versus platform threads
10,000 tasks that each wait 100 ms (standing in for a database or HTTP call):
10,000 tasks that each wait 100 ms: 200 platform threads 5289 ms | a virtual thread each 158 ms
With a pool of 200 OS threads, at most 200 tasks wait at once, so 10,000 tasks take 50 rounds of 100 ms. With a virtual thread per task, all 10,000 wait simultaneously; a blocked virtual thread unmounts from its carrier OS thread, costing a few hundred bytes of heap rather than a megabyte of stack. That's the 33× that made thread-per-request servers competitive with reactive ones again. Virtual threads don't make CPU-bound work faster (there are still only 2 cores), and they make it easy to overwhelm a downstream resource: 10,000 concurrent tasks against a pool of 20 database connections need a semaphore or the pool's own limit (chapters 49 and 52).
Experiment 4: pinning on JDK 21, fixed in JDK 24
Fifty virtual threads, each sleeping 100 ms while holding its own synchronized lock, with the scheduler limited to 2 carrier threads:
Java 21, 2 carrier threads: 50 virtual threads sleeping 100 ms inside synchronized took 2581 ms
Java 25, 2 carrier threads: 50 virtual threads sleeping 100 ms inside synchronized took 149 ms
On JDK 21, a virtual thread that blocks inside synchronized pins its carrier: it can't unmount, so the 2 carriers ran the tasks 2 at a time (25 rounds × 100 ms). JDK 24's JEP 491 reimplemented object monitors so virtual threads can unmount while holding them, and the same class file finished in one round on JDK 25. If you're on JDK 21, replace synchronized around blocking calls with ReentrantLock (or upgrade), and look for pinning with -Djdk.tracePinnedThreads=full (removed in 24) or the jdk.VirtualThreadPinned JFR event. Native calls and class initialisers can still pin on JDK 25.
Experiment 5: check-then-act on a concurrent map
Eight threads ask for the same expensive cached report at the same moment:
if (!cache.containsKey("report")) { build(); cache.put("report", …); } // check, then act
cache.computeIfAbsent("report", k -> build()); // atomic per key
containsKey-then-put built it 8 time(s)
computeIfAbsent built it 1 time(s)
Each operation on a ConcurrentHashMap is thread-safe, but a sequence of them isn't: all eight threads saw the key missing before any of them put it. In production this is the cache stampede: a popular entry expires and every request rebuilds it at once, hammering the database. computeIfAbsent locks that one key while building (so keep the function short and never touch the same map inside it); distributed caches need the equivalents covered in chapter 53 (request coalescing, locks, early refresh).
Try it yourself
- Remove
volatilebut putSystem.out.print("")inside the loop of experiment 1. Does it stop now? Why is that not a fix? - Fix experiment 2 by ordering locks with
System.identityHashCode, then bytryLock(50, MILLISECONDS)with retry. Which is simpler to get right? - In experiment 3, add a
Semaphore(20)around the sleep. How long do 10,000 tasks take now, and why is that the realistic number for a 20-connection pool? - Write experiment 1 in Go with a plain
booland run it withgo run -race. Then write it in Rust and read the compiler's error.
Revision sheet: concurrency
Key ideas
- Concurrency vs parallelism; threads share the heap; the hazards are races, visibility, ordering, deadlock, livelock, starvation.
- Java memory model: happens-before from locks,
volatile,finalfields,Thread.start/join, executors and concurrent collections; safe publication; double-checked locking needsvolatile. - Primitives:
synchronized(reentrant monitor),ReentrantLock/ReadWriteLock/StampedLock, atomics andLongAdder,Semaphore,CountDownLatch,CyclicBarrier,Phaser,BlockingQueues. - Executors: fixed/cached/scheduled pools,
ForkJoinPool(work stealing), virtual-thread-per-task;Future,CompletableFuturecomposition, timeouts and cancellation (interruption). - Virtual threads (JDK 21): cheap, JVM-scheduled; for blocking I/O; pinning in
synchronizedfixed by JEP 491 (JDK 24); limit downstream concurrency with semaphores. - Structured concurrency (
StructuredTaskScope, preview) and scoped values (final in JDK 25) for request-scoped data. - Other models: Go goroutines and channels, Erlang/Elixir actors, Rust ownership (
Send/Sync) and async, C#/JS/Kotlin async-await and coroutines, the reactive model (Reactor).
Numbers to remember
- Lab: a plain-field stop flag never stopped; 10,000 × 100 ms waits took 5,289 ms on 200 platform threads vs 158 ms on virtual threads; pinning: 2,581 ms on JDK 21 vs 149 ms on JDK 25; check-then-act built a cached value 8 times instead of 1.
- Platform thread stack about 1 MB reserved by default; a virtual thread starts at a few hundred bytes.
Pitfalls
- Shared mutable state without a lock or atomic; compound check-then-act operations.
- Missing
volatileon flags; publishing objects before construction finishes. - Nested locks in inconsistent order; holding locks during I/O or callbacks.
- Swallowing
InterruptedException(restore the interrupt flag). - Unbounded queues and pools; virtual threads overwhelming a connection pool;
ThreadLocalcaches multiplied by millions of virtual threads. parallelStreamandCompletableFuture.supplyAsyncwithout an executor, sharing the common pool.
Glossary
- Race condition: correctness depends on timing.
- Happens-before: the JMM ordering that guarantees visibility.
- CAS: compare-and-swap, an atomic hardware instruction.
- Carrier thread: an OS thread running virtual threads.
- Pinning: a virtual thread unable to unmount from its carrier while blocked.
- Work stealing: idle threads take tasks from busy threads' queues.