Java NotesRohit’s interview study guide
Chapter 09

Concurrency and Virtual Threads

How Java runs many things at once with real threads that share memory, why that's different from Node's single event loop, the bugs it brings (races, visibility, deadlocks) and the tools that fix them: synchronized, atomics, locks, thread pools, CompletableFuture, virtual threads (Java 21), scoped values and structured concurrency. Every example was run with Java 25 (Eclipse Temurin 25.0.5.1) on an 18-core Mac; the JavaScript comparison was run with Node 26.

Try it yourself. For each example, make an empty folder, save every code box in it under the name in its caption, and type the $ lines of the Terminal box in that folder. The examples are compact source files (chapter 01), which import the whole java.base module automatically, so java.util.concurrent, its atomic and locks packages need no import lines. Concurrency output can't show raw timings or thread numbers (they change every run), so the programs print a stable conclusion instead, such as lost updates: true.

10 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#Threads compared with the Node.js event loop

Added

In Node.js, your JavaScript runs on one thread. The event loop takes the next callback off a queue, runs it to the end, and takes the next. Waiting (for a socket, a file, a timer) happens outside your code, in libuv and the operating system, so one thread can juggle thousands of slow requests. The price is that one CPU-heavy callback stops everything: while it runs, no other request is served, and you reach for worker threads or more processes.

Java starts from the opposite end. A Java program can run many threads at once, truly in parallel on all cores, and they all share the same heap. Every object one thread can reach, another thread can read and change at the same moment. A thread that blocks (sleeps, waits for the database) just stops; the operating system runs the other threads meanwhile. That's why classic Java servers are thread-per-request: Tomcat, which Spring Boot uses by default, serves each request on its own thread from a pool of up to 200 (server.tomcat.threads.max, default 200 in Spring Boot 4.2), and your code is plain blocking code with no await anywhere.

The mental model: Node is one very fast waiter running between all the tables; Java is a waiter per table. A waiter per table needs no clever scheduling and can do heavy work without holding anyone up, but waiters are expensive (each platform thread is an OS thread with its own stack), and two waiters can grab the same plate. That second problem, shared mutable memory, is what most of this chapter is about.

Node.jsJava
Your code runs onone thread (plus optional worker threads)as many threads as you start
Waiting for I/Oawait: the thread moves onblocking call: this thread waits, others run
CPU-heavy workblocks every requestruns in parallel on other cores
Memory between threadsnot shared (workers pass messages; SharedArrayBuffer aside)shared by default: the same objects
Typical buga callback that blocks the loop; a logical race across an awaita data race: two threads changing one object
Cheap concurrencybuilt in (the event loop)virtual threads (Java 21), later in this chapter

Here is the difference made visible: a CPU-heavy job and three quick "requests". In Java the heavy job runs on its own thread and the requests are served while it works. The same program in Node serves nothing until the heavy job ends.

Waiters.java
void main() throws InterruptedException {
    var log = Collections.synchronizedList(new ArrayList<String>());

    Thread report = Thread.ofPlatform().name("report").start(() -> {
        long end = System.nanoTime() + 1_000_000_000L;   // 1 s of pure CPU work
        while (System.nanoTime() < end) { }
        log.add("report done");
    });

    for (int i = 1; i <= 3; i++) {
        log.add("request " + i + " served");
        Thread.sleep(100);
    }
    report.join();
    IO.println(log);
}
Terminal
$ java Waiters.java
[request 1 served, request 2 served, request 3 served, report done]
waiters.mjs
const log = [];

setTimeout(() => {
  const end = Date.now() + 1000;   // 1 s of pure CPU work
  while (Date.now() < end) { }
  log.push("report done");
}, 0);

for (let i = 1; i <= 3; i++) {
  setTimeout(() => log.push(`request ${i} served`), 10 + i * 100);
}
setTimeout(() => console.log(log), 1500);
Terminal
$ node waiters.mjs
[
  'report done',
  'request 1 served',
  'request 2 served',
  'request 3 served'
]
What’s happening
  1. Java: Thread.ofPlatform().name("report").start(…) (the builder API, Java 21) creates an OS thread and starts it. From now on two threads run at once: report spins the CPU for one second, and main carries on with the loop.
  2. main "serves" a request every 100 ms. Thread.sleep(100) blocks only main; report keeps running on another core. The three requests are logged at roughly 0, 100 and 200 ms, long before the report ends.
  3. report.join() makes main wait until the report thread has finished, so the report's entry is in the list before it's printed: [request 1 served, request 2 served, request 3 served, report done].
  4. Both threads add to the same list object. That's normal in Java, and it's why the list is wrapped in Collections.synchronizedList: a plain ArrayList isn't safe when two threads change it at once (the next topic shows what goes wrong).
  5. Node: the report callback runs first and holds the only thread for a full second. The request timers are due at 110, 210 and 310 ms, but nothing can run until the busy loop ends, so they all fire late and 'report done' is first in the list Node prints.
  6. Neither is "better": Node's model needs no locks because nothing runs in parallel; Java's model uses every core but makes shared data your problem.
AdvancedPlatform threads: what they cost

A platform thread (the only kind before Java 21) is a thin wrapper around an operating-system thread. Each one reserves its own stack (the -Xss default is 2 MB on macOS and Linux on ARM, 1 MB on x64, per the java man page), and the OS schedules them. A few hundred are fine; tens of thousands strain memory and scheduling. That cost is why Java code has used thread pools for 20 years (reuse a small set of threads for many tasks), and why virtual threads (later in this chapter) were added: threads cheap enough to have one per task again.

#Race conditions, synchronized and volatile

Added

A race condition is a bug whose result depends on how threads happen to interleave. The classic one is count++. It looks like one step, but it's three: read count, add one, write it back. If two threads both read 41, both write 42, and one increment is lost. In Node this can't happen inside a function, because nothing interrupts it; in Java it happens all the time.

The fix is mutual exclusion: only one thread at a time may run the read-add-write. Java's built-in tool is synchronized. Every object has a monitor (a lock), and synchronized (lock) { … } or a synchronized method takes it on entry and releases it on exit, even when an exception is thrown. A second thread that reaches the block waits until the first leaves.

The mental model: synchronized is a room with one key. Only the thread holding the key can be inside, and everything the previous key-holder wrote is visible to the next one who enters. That second half matters as much as the first, as the volatile example below shows.

Race.java
int count = 0;
int safeCount = 0;
final Object lock = new Object();

void main() throws InterruptedException {
    var threads = new ArrayList<Thread>();
    for (int t = 0; t < 4; t++) {
        threads.add(Thread.ofPlatform().start(() -> {
            for (int i = 0; i < 1_000_000; i++) {
                count++;                       // read, add, write: not atomic
                synchronized (lock) {
                    safeCount++;               // one thread at a time
                }
            }
        }));
    }
    for (var thread : threads) {
        thread.join();
    }
    IO.println("count: lost updates: " + (count < 4_000_000));
    IO.println("safeCount: " + safeCount);
}
Terminal
$ java Race.java
count: lost updates: true
safeCount: 4000000
What’s happening
  1. Four threads each increment two counters a million times, so both should end at 4,000,000.
  2. count++ compiles to a read of the field, an add and a write. Two threads on two cores often read the same value and both write value + 1, so increments vanish. When this was written it ended anywhere between about 1.1 and 2.4 million over a dozen runs; the program prints the stable fact, lost updates: true.
  3. safeCount++ sits inside synchronized (lock). A thread must hold lock's monitor to enter, so the three steps never overlap, and no increment is lost: safeCount: 4000000, every run.
  4. thread.join() matters too: it waits for each thread, and it guarantees main sees everything the thread wrote (a "happens-before" edge, below). Without it, main could print while the threads are still counting.
  5. The lock is a dedicated final Object. Any object works, but a private lock object means no outside code can lock it by accident (a synchronized method locks this, which callers can also lock).
AdvancedVisibility and volatile

Races aren't only about lost updates. A thread may never see another thread's write at all. The JIT compiler is allowed to keep a field in a register, and the CPU has caches; without synchronisation, nothing obliges one thread's write to reach another thread. The rules for when a write must be visible are the Java Memory Model (JLS chapter 17), and its key idea is happens-before: a write is guaranteed visible to a read only if the write happens-before the read.

The java.util.concurrent documentation lists the edges you'll use: an unlock of a monitor happens-before every later lock of the same monitor; a write to a volatile field happens-before every later read of that field; Thread.start() happens-before anything in the started thread; everything in a thread happens-before another thread returns from join() on it; and handing a task to an executor, putting an object into a concurrent collection, or Future.get() create the same kind of edge.

Visibility.java
boolean running = true;          // change to: volatile boolean running = true;

void main() throws InterruptedException {
    var worker = Thread.ofPlatform().daemon().start(() -> {
        long spins = 0;
        while (running) {
            spins++;
        }
        IO.println("worker saw running = false");
    });
    Thread.sleep(500);
    running = false;
    worker.join(2000);           // wait at most 2 s
    IO.println("worker still spinning 2 s later: " + worker.isAlive());
}
Terminal
$ java Visibility.java
worker still spinning 2 s later: true
$ sed -i '' 's/^boolean running/volatile boolean running/' Visibility.java
$ java Visibility.java
worker saw running = false
worker still spinning 2 s later: false
What’s happening
  1. The worker spins while running is true. After half a second main sets it to false and waits up to 2 s for the worker to stop.
  2. First run: the worker never stops: worker still spinning 2 s later: true. Nothing in the loop synchronises, so the JIT compiler (which compiles this hot loop within milliseconds) is allowed to read running once and keep using that value. The program only exits because the worker is a daemon thread, which doesn't keep the JVM alive.
  3. The sed line adds volatile to the field. (sed -i '' is the macOS form; on Linux it's sed -i.)
  4. Second run: the worker stops at once and prints worker saw running = false, then main prints false. A volatile write happens-before every later read of that field, so the JIT must read the field from memory on every loop iteration.
  5. The first result is what HotSpot did here; the memory model permits the stale read rather than requiring it, so another JVM or a slower machine might behave differently. That's the nasty part of visibility bugs: they come and go.
Advancedvolatile is not atomic

volatile fixes visibility only. volatile int count; count++ still loses updates, because the read, add and write are still three steps that can interleave. Use volatile for a flag one thread writes and others read (a stop signal, a "config reloaded" reference); use synchronized or an atomic (next topic) for read-modify-write.

"Is this counter thread-safe?"
Java
class Hits {
    private volatile int count;
    void hit() { count++; }
    int get() { return count; }
}
Show answer

No. volatile makes every write visible to other threads, but count++ is still a read, an add and a write. Two threads can both read 7 and both write 8.

What’s happening
  1. Thread A reads count (7). Thread B reads count (7): both reads are perfectly visible, volatile did its job.
  2. A writes 8, B writes 8. One hit is lost, exactly like the Race.java example.
  3. Fixes: make hit() and get() synchronized, or use AtomicInteger.incrementAndGet(), or LongAdder.increment() for a busy counter (next topic).
AdvancedGotcha: locking different objects

#Atomics and locks

Added

synchronized is the simplest tool, but java.util.concurrent (Java 5, the release Rohit last used, and much grown since) has finer ones:

  • Atomic classes (AtomicInteger, AtomicLong, AtomicReference) update one value without a lock, using the CPU's compare-and-set instruction: "set it to 8 only if it's still 7", retried until it succeeds. incrementAndGet() is the atomic count++.
  • LongAdder (Java 8) is a counter built for heavy contention: it spreads updates over several cells and adds them up when you call sum(). The Javadoc's rule: prefer it to AtomicLong when many threads update a common sum used for statistics, "not for fine-grained synchronization control".
  • ReentrantLock is synchronized as an object: lock() and unlock() (always in finally), plus what synchronized can't do: tryLock() with a timeout, interruptible waiting, fairness, and several Conditions.
  • ReentrantReadWriteLock lets many readers in at once but a writer alone, for data that's read far more than written.

The mental model: an atomic is a turnstile for one number; a lock is a door for a whole block of code. If all you need is "add one" or "swap this reference", an atomic is simpler and faster. If several fields must change together (move money from one balance to another), you need a lock around both.

Counters.java
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

void main() throws InterruptedException {
    var atomic = new AtomicInteger();
    var adder = new LongAdder();

    var threads = new ArrayList<Thread>();
    for (int t = 0; t < 4; t++) {
        threads.add(Thread.ofPlatform().start(() -> {
            for (int i = 0; i < 1_000_000; i++) {
                atomic.incrementAndGet();
                adder.increment();
            }
        }));
    }
    for (var thread : threads) {
        thread.join();
    }
    IO.println("AtomicInteger: " + atomic.get());
    IO.println("LongAdder:     " + adder.sum());

    // compare-and-set: change the value only if it's still what you expect
    IO.println("CAS 4000000 -> 0: " + atomic.compareAndSet(4_000_000, 0));
    IO.println("CAS 4000000 -> 1: " + atomic.compareAndSet(4_000_000, 1));
    IO.println("now: " + atomic.get());
}
Terminal
$ java Counters.java
AtomicInteger: 4000000
LongAdder:     4000000
CAS 4000000 -> 0: true
CAS 4000000 -> 1: false
now: 0
What’s happening
  1. The same four threads and four million increments as in Race.java, but on an AtomicInteger and a LongAdder. (The two imports are redundant in a compact source file; they're there so you can see where the classes live.)
  2. incrementAndGet() reads, adds and writes as one indivisible step, using the CPU's compare-and-set in a retry loop. No increment is lost: AtomicInteger: 4000000.
  3. LongAdder.increment() adds to one of several internal cells (different threads tend to hit different cells, so they don't fight over one memory location), and sum() adds the cells: 4000000.
  4. compareAndSet(4_000_000, 0) succeeds because the value really is 4,000,000, and sets it to 0: true.
  5. The second compareAndSet(4_000_000, 1) fails because the value is now 0, and changes nothing: false, now: 0. That "only if unchanged" check is the building block of every lock-free algorithm: read, compute, CAS, and retry if someone else got there first.
AdvancedReentrantLock and tryLock

The one thing synchronized can never do is give up. A thread waiting for a monitor waits forever. ReentrantLock.tryLock(timeout) waits a bounded time and tells you whether it got the lock, which is how you avoid hanging on a lock and how you break deadlocks (last topic).

Locks.java
import java.util.concurrent.locks.ReentrantLock;

void main() throws Exception {
    var lock = new ReentrantLock();
    var holding = new CountDownLatch(1);
    var release = new CountDownLatch(1);

    var owner = Thread.ofPlatform().start(() -> {
        lock.lock();
        try {
            holding.countDown();         // tell main: I have the lock
            release.await();             // keep it until main says so
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock.unlock();               // always in finally
        }
    });

    holding.await();
    IO.println("got it while owner holds it: " + lock.tryLock(200, TimeUnit.MILLISECONDS));

    release.countDown();
    owner.join();
    IO.println("got it after owner released it: " + lock.tryLock(200, TimeUnit.MILLISECONDS));
    IO.println("held by main: " + lock.isHeldByCurrentThread());
    lock.unlock();
}
Terminal
$ java Locks.java
got it while owner holds it: false
got it after owner released it: true
held by main: true
What’s happening
  1. Two CountDownLatches make the order deterministic: a latch is a one-shot gate, await() blocks until countDown() has been called as many times as the latch's count (here 1).
  2. The owner thread takes the lock and opens holding, so main knows the lock is taken before it tries.
  3. tryLock(200, MILLISECONDS) waits up to 200 ms, can't get the lock, and returns false instead of blocking forever.
  4. main opens release; the owner leaves its try and unlocks in finally. Forgetting that unlock() is the classic ReentrantLock bug: unlike synchronized, nothing releases the lock for you when an exception is thrown.
  5. Now tryLock succeeds: true, and isHeldByCurrentThread() confirms main holds it. "Reentrant" means the holder may lock it again without deadlocking itself (it then has to unlock twice); synchronized is reentrant too.
AdvancedWhich tool when
NeedUse
A flag or a reference that one thread writes and others readvolatile
A counter or one value updated by many threadsAtomicInteger / AtomicLong / AtomicReference
A hot statistics counter (requests served)LongAdder
Several fields that must change togethersynchronized (simplest)
A timeout, interruptible wait, fairness or several conditionsReentrantLock
Mostly reads, occasional writes, reads that take a whileReentrantReadWriteLock
Shared maps, queues, listsa concurrent collection (later in this chapter)

Since Java 24 (JEP 491), synchronized no longer pins virtual threads, so the old advice "replace synchronized with ReentrantLock for virtual threads" is out of date; the JEP now says to choose between them "based solely upon which best solves the problem at hand". More on that under virtual threads.

#ExecutorService and thread pools

Added

Starting a thread per task by hand doesn't scale and doesn't give results back. An ExecutorService separates what to run from how: you submit tasks (Runnable for no result, Callable<T> for a result or a checked exception) and get Futures back; the executor decides which thread runs them. The Executors factory gives the usual pools:

  • newFixedThreadPool(n): n threads and an unbounded queue; tasks beyond n wait. The workhorse for CPU-bound work (n ≈ number of cores).
  • newCachedThreadPool(): creates threads as needed and reuses idle ones; threads idle for 60 seconds are removed. Dangerous under load, because there's no upper limit.
  • newScheduledThreadPool(n): runs tasks after a delay or periodically, Java's setTimeout / setInterval.
  • newVirtualThreadPerTaskExecutor() (Java 21): a new virtual thread per task, no pooling. Covered below.

The mental model for a Node developer: an executor is a worker pool you hand jobs to, like Piscina for worker_threads, except the workers share memory with you. And since Java 19, ExecutorService is AutoCloseable: close() stops accepting tasks and waits for the submitted ones, so a try-with-resources block replaces the old shutdown() + awaitTermination() dance.

Pool.java
void main() throws Exception {
    List<Callable<Integer>> tasks = new ArrayList<>();
    var threadsUsed = ConcurrentHashMap.<String>newKeySet();
    for (int n = 1; n <= 10; n++) {
        int x = n;
        tasks.add(() -> {
            threadsUsed.add(Thread.currentThread().getName());
            Thread.sleep(50);             // pretend to work
            return x * x;
        });
    }

    try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
        List<Future<Integer>> futures = pool.invokeAll(tasks);
        int total = 0;
        for (var f : futures) {
            total += f.get();
        }
        IO.println("sum of squares 1..10: " + total);
        IO.println("10 tasks ran on at most 4 threads: " + (threadsUsed.size() <= 4));

        Future<Integer> failing = pool.submit(() -> Integer.parseInt("ten"));
        try {
            failing.get();
        } catch (ExecutionException e) {
            IO.println("get() threw ExecutionException, cause: " + e.getCause());
        }
    } // close(): no new tasks, wait for running ones
    IO.println("pool closed");
}
Terminal
$ java Pool.java
sum of squares 1..10: 385
10 tasks ran on at most 4 threads: true
get() threw ExecutionException, cause: java.lang.NumberFormatException: For input string: "ten"
pool closed
What’s happening
  1. Ten Callable<Integer> tasks each square a number. int x = n; copies the loop variable because a lambda may only capture effectively final variables (chapter 08).
  2. invokeAll submits all ten to the pool of 4 and waits until every one is done. Six tasks queue while the first four run. The futures come back in the order of the tasks, whatever order they finished in, so the sum is 1 + 4 + … + 100 = 385.
  3. Each task records its thread's name in a concurrent set. The names (pool-1-thread-1 …) vary between runs, so the program prints only the fact that matters: at most 4 distinct threads ran 10 tasks, true. That's the point of a pool: threads are reused.
  4. The failing task throws NumberFormatException on a pool thread. The exception doesn't crash anything there; it's stored in the Future, and get() rethrows it wrapped in ExecutionException, with the original as the cause.
  5. Leaving the try block calls close(): no more tasks are accepted, and it waits for running ones. Only then is pool closed printed.
AdvancedScheduled tasks: setInterval in Java
Ticker.java
void main() throws InterruptedException {
    var ticks = new CountDownLatch(3);
    try (var scheduler = Executors.newScheduledThreadPool(1)) {
        var counter = new AtomicInteger();
        scheduler.scheduleAtFixedRate(() -> {
            IO.println("tick " + counter.incrementAndGet());
            ticks.countDown();
        }, 0, 100, TimeUnit.MILLISECONDS);

        ticks.await();                    // wait for three ticks
        scheduler.shutdownNow();          // cancel the repeating task
    }
    IO.println("stopped");
}
Terminal
$ java Ticker.java
tick 1
tick 2
tick 3
stopped
What’s happening
  1. scheduleAtFixedRate(task, 0, 100, MILLISECONDS) runs the task now and then every 100 ms, like setInterval(task, 100). With one scheduler thread the ticks run one after another, so they always print in order.
  2. main waits on a latch that the third tick opens.
  3. shutdownNow() cancels the repeating task. Without it, close() would wait forever: a periodic task never "finishes". This is clearInterval.
  4. The executor is closed and stopped prints. In a Spring app you'd write @Scheduled(fixedRate = 100) on a method instead, and Spring runs the scheduler for you.
AdvancedSizing a pool, and the queue nobody watches
  • CPU-bound tasks: about one thread per core (Runtime.getRuntime().availableProcessors()); more threads only add switching.
  • Blocking I/O tasks (HTTP calls, JDBC): many more threads than cores, because most are waiting. This is exactly the case virtual threads now handle better than any pool size.
  • The unbounded queue: newFixedThreadPool queues without limit. If tasks arrive faster than they finish, the queue grows until the heap runs out. Production code that takes work from outside builds a ThreadPoolExecutor with a bounded ArrayBlockingQueue and a rejection policy, so overload fails fast instead of slowly.
  • Shut pools down. Pool threads are non-daemon threads, so a pool you never shut down keeps the JVM running after main returns. try-with-resources (Java 19+) makes that automatic.

#CompletableFuture compared with Promise

Added

A plain Future can only be waited on with a blocking get(). CompletableFuture (Java 8) adds what a JavaScript developer expects from a Promise: you chain what happens next, combine several, and handle errors in the chain. The mapping is close enough to learn it by translation:

JavaScript PromiseJava CompletableFuture
new Promise(…) running workCompletableFuture.supplyAsync(() -> value)
Promise.resolve(v)CompletableFuture.completedFuture(v)
.then(v => v + 1) (returns a value).thenApply(v -> v + 1)
.then(v => fetchMore(v)) (returns a promise).thenCompose(v -> fetchMore(v))
Promise.all([a, b]) then combinea.thenCombine(b, (x, y) -> …) or CompletableFuture.allOf(a, b)
.catch(e => fallback).exceptionally(e -> fallback)
.finally(…).whenComplete((v, e) -> …)
await pp.join() (blocks this thread)

Where the comparison breaks: a promise runs on the one event-loop thread; a CompletableFuture runs on real threads. supplyAsync without an executor runs on ForkJoinPool.commonPool(), a pool shared by the whole JVM and sized from the core count (ForkJoinPool.getCommonPoolParallelism() returned 17 on this 18-core Mac), which is the wrong place for blocking I/O. join() really blocks a thread, where await only suspends a function. And the Java split between thenApply and thenCompose is the same split as map and flatMap: JavaScript's .then quietly does both.

Checkout.java
record Product(String name, int priceCents) {}

void pause(int ms) {
    try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); }
}

CompletableFuture<Product> findProduct(String id, Executor io) {
    return CompletableFuture.supplyAsync(() -> { pause(1000); return new Product("Keyboard", 4999); }, io);
}

CompletableFuture<Integer> stockFor(String id, Executor io) {
    return CompletableFuture.supplyAsync(() -> { pause(1000); return 3; }, io);
}

CompletableFuture<Integer> discountFor(Product p, Executor io) {
    return CompletableFuture.supplyAsync(() -> { pause(500); return p.priceCents() > 4000 ? 10 : 0; }, io);
}

void main() {
    try (var io = Executors.newVirtualThreadPerTaskExecutor()) {
        long start = System.nanoTime();

        CompletableFuture<String> page = findProduct("p1", io)
                .thenCompose(p -> discountFor(p, io)
                        .thenApply(pct -> p.name() + " at " + pct + "% off"))
                .thenCombine(stockFor("p1", io), (offer, stock) -> offer + ", " + stock + " left");

        IO.println(page.join());
        long ms = (System.nanoTime() - start) / 1_000_000;
        IO.println("product and stock fetched in parallel (under 2,200 ms): " + (ms < 2200));

        String fallback = CompletableFuture
                .supplyAsync(() -> Integer.parseInt("lots"), io)
                .thenApply(n -> "stock: " + n)
                .exceptionally(e -> "stock unknown (" + e.getCause().getClass().getSimpleName() + ")")
                .join();
        IO.println(fallback);
    }
}
Terminal
$ java Checkout.java
Keyboard at 10% off, 3 left
product and stock fetched in parallel (under 2,200 ms): true
stock unknown (NumberFormatException)
What’s happening
  1. Each "remote call" is supplyAsync(supplier, io): it starts immediately on a thread from io and returns a CompletableFuture at once, like calling an async function without await. The executor here is a virtual-thread executor (later in this chapter), the right place for blocking calls; without it they'd run on the shared common pool.
  2. findProduct and stockFor start at the same time. thenCompose waits for the product, then starts discountFor with it and flattens the result, because discountFor returns another future. (thenApply there would give a CompletableFuture<CompletableFuture<Integer>>, the Java version of a promise of a promise.)
  3. thenApply turns the discount into text: Keyboard at 10% off. thenCombine waits for that and the stock call, then joins the two values: Keyboard at 10% off, 3 left.
  4. Product (1 s) then discount (0.5 s) is about 1.5 s, while the stock call (1 s) runs alongside, so the whole page takes about 1.5 s, not the 2.5 s that one call after another would take: true. (The delays are long so the check stays reliable on a busy machine.)
  5. In the second chain, parseInt("lots") throws. The thenApply step is skipped (like a .then after a rejection), and exceptionally gets the error and returns a fallback. The error arrives wrapped in a CompletionException, so e.getCause() is the real NumberFormatException.
  6. join() blocks main until the result is ready, which is fine at the top of a program or a test. In a request handler you'd return the future (Spring MVC accepts a CompletableFuture return value) or, with virtual threads, just write blocking code and skip futures altogether.
AdvancedWhere the comparison breaks: callbacks can run right away

In JavaScript, .then callbacks always run later, as a microtask, even on an already-resolved promise. In Java, a thenApply on a future that's already complete runs immediately, on the thread that calls thenApply. And a failed future that nobody joins fails silently: there's no unhandledRejection warning.

Order.java
void main() {
    var done = CompletableFuture.completedFuture(1);
    done.thenApply(x -> {
        IO.println("callback");
        return x + 1;
    });
    IO.println("after thenApply");

    CompletableFuture.runAsync(() -> {
        throw new IllegalStateException("boom");
    });
    IO.println("nobody heard the boom");
}
Terminal
$ java Order.java
callback
after thenApply
nobody heard the boom
order.mjs
const done = Promise.resolve(1);
done.then((x) => {
  console.log("callback");
  return x + 1;
});
console.log("after then");

Promise.reject(new Error("boom"));
console.log("did anyone hear the boom?");
Terminal
$ node order.mjs
after then
did anyone hear the boom?
callback
file://<project>/order.mjs:8
Promise.reject(new Error("boom"));
               ^

Error: boom
    at file://<project>/order.mjs:8:16
    at ModuleJob.run (node:internal/modules/esm/module_job:569:25)
    at async node:internal/modules/esm/loader:650:26
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5)

Node.js v26.7.0
What’s happening
  1. Java: done is already complete, so thenApply runs the callback on the spot, on main: callback prints before after thenApply.
  2. Node: the .then callback is queued as a microtask, which runs only after the current script finishes: after then and did anyone hear the boom? come first, then callback.
  3. Java: the runAsync task throws on a common-pool thread. The exception is stored in a future that nobody keeps or joins, so it's lost without a trace and the program exits normally.
  4. Node: once the microtasks have run, the unhandled rejection crashes the process (the default since Node 15): it prints Error: boom with its stack and exits with status 1.
  5. The lessons: don't assume a Java callback runs on another thread, use the …Async variants (thenApplyAsync) when you need that, and always end a chain with exceptionally, handle or whenComplete that logs, or join it.

#Virtual threads

Added

A virtual thread (final in Java 21, JEP 444) is a java.lang.Thread that the JDK schedules instead of the operating system. Many virtual threads take turns on a few carrier threads (platform threads in a ForkJoinPool whose size defaults to the number of cores). When a virtual thread blocks on I/O, a sleep, a lock or a BlockingQueue.take(), the JDK unmounts it: its stack is saved on the heap and the carrier picks up another virtual thread. When the I/O completes, the virtual thread is mounted again, possibly on a different carrier, and continues where it left off.

For a Node developer this is the most important idea in the chapter: virtual threads give Java the event loop's scalability without async/await. Under the hood it is an event loop: the JDK waits for sockets with the OS's non-blocking APIs, like libuv does. But your code stays straight-line blocking code: var user = repo.findUser(id); var orders = client.fetchOrders(user);. No callback, no colouring of functions into async and sync. The JEP's own summary is that virtual threads are not faster threads: they give scale (many concurrent waiting tasks), not speed.

The mental model: a platform thread is a taxi with its own driver, waiting outside while you shop; a virtual thread is a passenger who gets out when they stop, so a few drivers (carriers) can serve thousands of passengers.

Scale.java
void main() throws InterruptedException {
    long tomcatLike = secondsToRun(Executors.newFixedThreadPool(200), 1_000);
    IO.println("1,000 tasks on 200 platform threads took at least 5 s: " + (tomcatLike >= 5));

    long virtual = secondsToRun(Executors.newVirtualThreadPerTaskExecutor(), 10_000);
    IO.println("10,000 tasks on virtual threads finished in under 3 s: " + (virtual < 3));
}

long secondsToRun(ExecutorService executor, int tasks) {
    long start = System.nanoTime();
    try (executor) {
        for (int i = 0; i < tasks; i++) {
            executor.submit(() -> {
                Thread.sleep(Duration.ofSeconds(1));   // stands in for a 1 s database or HTTP call
                return null;
            });
        }
    } // close() waits for every task
    return Duration.ofNanos(System.nanoTime() - start).toSeconds();
}
Terminal
$ java Scale.java
1,000 tasks on 200 platform threads took at least 5 s: true
10,000 tasks on virtual threads finished in under 3 s: true
What’s happening
  1. Each task "calls a slow service" by sleeping for one second. Thread.sleep is a blocking call, exactly like a JDBC query or an HTTP request.
  2. 200 platform threads, the size of Tomcat's default pool: 1,000 tasks run 200 at a time, in five waves of one second, so it takes at least 5 s: true. Each waiting task holds a whole OS thread doing nothing.
  3. Virtual threads: newVirtualThreadPerTaskExecutor() starts a new virtual thread for every task, 10,000 of them. Each sleep unmounts its virtual thread, so a handful of carriers (18 on this Mac, one per core) keep all 10,000 waiting at once. All of them wake after about a second: under 3 s, true. Ten times the work in a fifth of the time.
  4. try (executor) (try-with-resources on an existing variable, Java 9) closes the executor at the end of the block, and close() waits for all tasks: that's what makes the timing meaningful.
  5. If the tasks were CPU work instead of waiting, virtual threads wouldn't help at all: there are still only 18 cores. That's the boundary of the idea.
AdvancedCreating virtual threads
Hello.java
void main() throws InterruptedException {
    Thread vt = Thread.ofVirtual().name("greeter").start(() ->
            IO.println("hello from " + Thread.currentThread().getName()
                    + ", virtual: " + Thread.currentThread().isVirtual()
                    + ", daemon: " + Thread.currentThread().isDaemon()));
    vt.join();

    Thread.startVirtualThread(() -> IO.println("short form")).join();
    IO.println("main is virtual: " + Thread.currentThread().isVirtual());
}
Terminal
$ java Hello.java
hello from greeter, virtual: true, daemon: true
short form
main is virtual: false
What’s happening
  1. Thread.ofVirtual() is a builder (Java 21) like Thread.ofPlatform(); .name("greeter").start(…) starts a named virtual thread. Unnamed virtual threads have an empty name.
  2. Inside, Thread.currentThread() is the virtual thread itself, never the carrier: virtual: true. The carrier is invisible to your code.
  3. Virtual threads are always daemon threads, so they never keep the JVM alive on their own: daemon: true. That's why the program joins them.
  4. Thread.startVirtualThread(runnable) is the one-line form.
  5. main runs on a platform thread: false. In practice you rarely create virtual threads yourself: you use newVirtualThreadPerTaskExecutor(), or a framework does it (Spring Boot: spring.threads.virtual.enabled=true runs each request on a virtual thread; chapter 13).
AdvancedPinning, and what Java 24 fixed

A virtual thread that can't unmount while it blocks is pinned: it holds its carrier, and if all carriers are pinned, every other virtual thread waits. In Java 21 to 23 the common cause was blocking inside synchronized (a synchronized method that does a JDBC call), so the advice everywhere was "replace synchronized with ReentrantLock". Java 24 (JEP 491) removed that: a virtual thread that blocks in a synchronized method or block, or in Object.wait(), now releases its carrier. On Java 25 that advice is outdated, and interviewers who know their stuff will check whether you know it.

Pinning.java
class Account {
    synchronized void slowUpdate() throws InterruptedException {
        Thread.sleep(1000);              // blocking while holding the monitor
    }
}

void main() {
    long start = System.nanoTime();
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
        for (int i = 0; i < 10_000; i++) {
            var account = new Account();
            executor.submit(() -> { account.slowUpdate(); return null; });
        }
    }
    long s = Duration.ofNanos(System.nanoTime() - start).toSeconds();
    IO.println("10,000 tasks sleeping inside synchronized finished in under 3 s: " + (s < 3));
}
Terminal
$ java Pinning.java
10,000 tasks sleeping inside synchronized finished in under 3 s: true
What’s happening
  1. Each task calls a synchronized method that blocks for a second while holding its object's monitor. Each task has its own Account, so there's no contention: the only question is whether blocking inside synchronized holds the carrier.
  2. On Java 25 it doesn't: each virtual thread unmounts inside slowUpdate, all 10,000 sleep at once, and the run ends after about a second: true.
  3. On Java 21 to 23, each sleep would have pinned its carrier (JEP 491 describes this: the blocked call "blocks not only the virtual thread but also its carrier"), so only as many tasks as carriers, about one per core, could sleep at a time. That wasn't run here: the checker has only Java 25.
  4. What still pins on Java 25, per JEP 491: native code (a native method or the Foreign Function & Memory API) that calls back into Java and blocks; blocking while a class is being loaded or initialised (inside a static {} initialiser, or waiting for another thread to initialise a class). JFR records a jdk.VirtualThreadPinned event when it happens; the old -Djdk.tracePinnedThreads option was removed.
AdvancedWhen not to use virtual threads
  • CPU-bound work. Virtual threads don't add cores. Use a fixed pool sized to the cores or a parallel stream.
  • Don't pool them. They're meant to be created per task and thrown away. A pool of 20 virtual threads to limit calls to a fragile service is the wrong tool; JEP 444 says to use a Semaphore (see the exercises).
  • Expensive ThreadLocals. Code that caches a costly object per thread (a formatter, a buffer, a connection) in a ThreadLocal creates one per task with virtual threads, because each task has its own thread. Use a shared, thread-safe object or a proper pool instead. For passing context, use scoped values (next topic).
  • Libraries that block in native code still pin (above), and a connection pool of 10 is still a limit of 10 concurrent queries, however many virtual threads wait for it.
"10,000 virtual threads each run a 1-second CPU loop on an 8-core machine. How long does it take?"
Java
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
    for (int i = 0; i < 10_000; i++) {
        ex.submit(() -> burnCpuFor(Duration.ofSeconds(1)));
    }
}
Show answer

About 10,000 / 8 = 1,250 seconds, the same as with 8 platform threads. Virtual threads only unmount when they block; a CPU loop never blocks, so each one keeps its carrier until it's done.

What’s happening
  1. The scheduler has 8 carriers, one per core.
  2. Each task computes for a full second and never waits, so nothing triggers an unmount.
  3. Eight tasks run at a time: 1,250 rounds of one second each. Virtual threads made the code no faster and no slower; for CPU-bound work, size a pool to the cores instead. (This one isn't run on the page: it would take 20 minutes.)

#Structured concurrency and scoped values

Added

Two newer APIs finish the virtual-thread story. Both solve problems a Node developer will recognise.

Scoped values (final in Java 25, JEP 506) pass context, such as the logged-in user or a request id, down a call chain without adding a parameter to every method. A ScopedValue is bound for the duration of one call with ScopedValue.where(KEY, value).run(…), can be read anywhere inside that call with KEY.get(), can't be changed, and is gone when the call returns. That's Node's AsyncLocalStorage (als.run(store, fn)), and the replacement for the old ThreadLocal, which is mutable, leaks if you forget remove(), and copies itself into child threads.

Structured concurrency (StructuredTaskScope) treats a group of concurrent subtasks as one unit of work with one lifetime: fork them inside a scope, join them, and by the time the scope closes every subtask has finished or been cancelled. If one fails, the others are cancelled automatically. Compare with Promise.all, which rejects as soon as one promise fails but leaves the others running with nobody listening; or with an ExecutorService where a failed task leaves its siblings running. It's still a preview in Java 25 (JEP 505, the fifth preview), so it needs --enable-preview. Its API changed again in Java 26 and 27 (JEP 533 reworked the type parameters and the joiners' exceptions) and it's targeted to become final, with the Java 27 API, in Java 28 (JEP 543, due March 2027). Learn the idea; expect the method signatures below to change.

Context.java
static final ScopedValue<String> USER = ScopedValue.newInstance();

void handle(String user) {
    ScopedValue.where(USER, user).run(() -> placeOrder());
}

void placeOrder() {
    audit("order placed");                 // no user parameter anywhere
    ScopedValue.where(USER, "system").run(() -> audit("stock reserved"));
    audit("payment taken");
}

void audit(String event) {
    IO.println(event + " by " + USER.get());
}

void main() {
    handle("rohit");
    IO.println("bound outside handle: " + USER.isBound());
    IO.println(USER.orElse("anonymous"));
    USER.get();
}
Terminal
$ java Context.java
order placed by rohit
stock reserved by system
payment taken by rohit
bound outside handle: false
anonymous
Exception in thread "main" java.util.NoSuchElementException: ScopedValue not bound
	at java.base/java.lang.ScopedValue.slowGet(ScopedValue.java:571)
	at java.base/java.lang.ScopedValue.get(ScopedValue.java:564)
	at Context.main(Context.java:21)
What’s happening
  1. USER is a key, usually a static final field. It holds no value by itself.
  2. handle binds USER to "rohit" for the duration of placeOrder(). Neither placeOrder nor audit takes a user parameter, yet audit reads it: order placed by rohit.
  3. Inside, a nested where(USER, "system") rebinds it for one inner call only: stock reserved by system. When that call returns, the outer binding is back: payment taken by rohit. Nobody can change a binding; you can only shadow it for a nested call.
  4. After handle returns, the binding is gone: isBound() is false, and orElse("anonymous") gives the fallback. There's nothing to clean up, unlike a ThreadLocal that stays set on a pooled thread until someone calls remove().
  5. USER.get() outside any binding throws NoSuchElementException: ScopedValue not bound, so a missing context fails loudly instead of quietly returning null.
AdvancedStructuredTaskScope (preview in Java 25)
Dashboard.java
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;

static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
static final AtomicBoolean inventoryCancelled = new AtomicBoolean();

record Dashboard(String user, int orders) {}

String findUser() throws InterruptedException {
    Thread.sleep(1000);
    return "Rohit (request " + REQUEST_ID.get() + ")";
}

int countOrders() throws InterruptedException {
    Thread.sleep(1000);
    return 3;
}

int checkInventory() throws InterruptedException {
    try {
        Thread.sleep(5000);
        return 42;
    } catch (InterruptedException e) {
        inventoryCancelled.set(true);
        throw e;
    }
}

int failingPrices() throws InterruptedException {
    Thread.sleep(100);
    throw new IllegalStateException("price service down");
}

Dashboard load() throws InterruptedException {
    try (var scope = StructuredTaskScope.open()) {
        Subtask<String> user = scope.fork(() -> findUser());
        Subtask<Integer> orders = scope.fork(() -> countOrders());
        scope.join();                      // waits for both; throws if either failed
        return new Dashboard(user.get(), orders.get());
    }
}

void loadWithFailure() throws InterruptedException {
    try (var scope = StructuredTaskScope.open()) {
        scope.fork(() -> checkInventory());
        scope.fork(() -> failingPrices());
        scope.join();
    } catch (StructuredTaskScope.FailedException e) {
        IO.println("failed: " + e.getCause().getMessage());
        IO.println("slow inventory call was cancelled: " + inventoryCancelled.get());
    }
}

void main() throws Exception {
    long start = System.nanoTime();
    Dashboard d = ScopedValue.where(REQUEST_ID, "r-17").call(() -> load());
    IO.println(d);
    IO.println("both calls ran at once (under 1,700 ms): " + ((System.nanoTime() - start) / 1_000_000 < 1700));

    start = System.nanoTime();
    loadWithFailure();
    IO.println("gave up without waiting 5 s: " + ((System.nanoTime() - start) / 1_000_000 < 2000));
}
Terminal
$ java Dashboard.java 2>&1 | head -4
Dashboard.java:1: error: StructuredTaskScope is a preview API and is disabled by default.
import java.util.concurrent.StructuredTaskScope;
                           ^
  (use --enable-preview to enable preview APIs)
$ java --enable-preview Dashboard.java
Dashboard[user=Rohit (request r-17), orders=3]
both calls ran at once (under 1,700 ms): true
failed: price service down
slow inventory call was cancelled: true
gave up without waiting 5 s: true
What’s happening
  1. StructuredTaskScope.open() (the Java 25 preview API; Java 21 to 24 used new StructuredTaskScope.ShutdownOnFailure()) opens a scope whose default policy is "all must succeed". fork starts each subtask in a new virtual thread and returns a Subtask handle.
  2. scope.join() waits for both. findUser and countOrders (1 s each) run at the same time, so the whole thing takes about 1 s, not 2: true. After join, user.get() and orders.get() are safe to call.
  3. findUser reads REQUEST_ID although it runs on a different (virtual) thread: subtasks inherit the scoped values bound where the scope was opened. ScopedValue.where(…).call(…) is the variant of run that returns a value. The result prints as Dashboard[user=Rohit (request r-17), orders=3].
  4. In loadWithFailure, failingPrices throws after 100 ms. The scope cancels the other subtask by interrupting it: checkInventory's 5-second sleep throws InterruptedException, which sets the flag.
  5. join() throws StructuredTaskScope.FailedException with the subtask's exception as its cause, and close() (the end of the try-with-resources) has already waited for the cancelled sibling to finish. So the catch block sees failed: price service down and slow inventory call was cancelled: true, and the method returns quickly instead of after 5 seconds.
  6. The first command shows what happens without --enable-preview: the file doesn't compile, and every use of the API is an error such as "StructuredTaskScope is a preview API and is disabled by default" (head -4 keeps the first of nine). With the flag, it compiles and runs. Compiling with javac needs both --release 25 --enable-preview, and running the class files needs java --enable-preview again.

#Concurrent collections

Added

The regular collections (ArrayList, HashMap) aren't thread-safe: two threads changing a HashMap at once can lose entries or corrupt its internals. Java has had three generations of answers:

  • Java 1.0: Vector and Hashtable, every method synchronized. Legacy; don't use them.
  • Java 1.2: Collections.synchronizedMap(map) wraps any map with one lock. Correct, but every reader and writer queues for that one lock, and iterating still needs a manual synchronized block.
  • Java 5 and later: java.util.concurrent, built for concurrency. ConcurrentHashMap allows any number of concurrent reads and many concurrent writes. CopyOnWriteArrayList copies the whole array on every write, so readers never lock. BlockingQueues (ArrayBlockingQueue, LinkedBlockingQueue) let producer threads hand work to consumer threads. Their iterators are weakly consistent: they never throw ConcurrentModificationException.

The trap that catches everyone: a thread-safe map makes each call safe, not a sequence of calls. map.put(word, map.get(word) + 1) is two calls with a gap between them, the same lost-update race as count++. ConcurrentHashMap has atomic compound methods for exactly this: merge, compute, computeIfAbsent, putIfAbsent.

WordCount.java
void main() throws InterruptedException {
    var racy = new ConcurrentHashMap<String, Integer>();
    var atomic = new ConcurrentHashMap<String, Integer>();
    racy.put("java", 0);

    var threads = new ArrayList<Thread>();
    for (int t = 0; t < 4; t++) {
        threads.add(Thread.ofPlatform().start(() -> {
            for (int i = 0; i < 100_000; i++) {
                racy.put("java", racy.get("java") + 1);   // check-then-act: two calls
                atomic.merge("java", 1, Integer::sum);   // one atomic call
            }
        }));
    }
    for (var thread : threads) {
        thread.join();
    }
    IO.println("get + put lost updates: " + (racy.get("java") < 400_000));
    IO.println("merge: " + atomic.get("java"));
}
Terminal
$ java WordCount.java
get + put lost updates: true
merge: 400000
What’s happening
  1. Both maps are ConcurrentHashMaps, so neither can be corrupted. The difference is how they're updated.
  2. racy.put("java", racy.get("java") + 1): between the get and the put, another thread can do its own get and put. Both write the same value + 1, and an update is lost: get + put lost updates: true.
  3. atomic.merge("java", 1, Integer::sum) does the whole thing as one atomic step inside the map: if the key is missing it stores 1, otherwise it stores old + 1, with no gap for another thread. 400,000 increments give merge: 400000.
  4. This is the same lesson as count++, one level up: thread-safe building blocks don't make your sequence of operations atomic.
AdvancedcomputeIfAbsent: a per-key cache

cache.computeIfAbsent(key, k -> load(k)) runs load at most once per key even when many threads ask at once, and the others wait for that one result. The Javadoc asks for the function to be "short and simple" and not to modify the map, because it runs while part of the map is locked. For anything slow or with expiry, use a real cache library (Caffeine, which Spring's @Cacheable can use; chapter 17).

AdvancedCopyOnWriteArrayList: iterate while others write
Listeners.java
void main() {
    var plain = new ArrayList<>(List.of("audit", "email"));
    try {
        for (var l : plain) {
            if (l.equals("audit")) plain.add("metrics");
        }
    } catch (ConcurrentModificationException e) {
        IO.println("ArrayList: ConcurrentModificationException");
    }

    var listeners = new CopyOnWriteArrayList<>(List.of("audit", "email"));
    for (var l : listeners) {
        IO.println("notify " + l);
        if (l.equals("audit")) listeners.add("metrics");
    }
    IO.println("after: " + listeners);
}
Terminal
$ java Listeners.java
ArrayList: ConcurrentModificationException
notify audit
notify email
after: [audit, email, metrics]
What’s happening
  1. Adding to an ArrayList while a for-each loop walks it makes the iterator fail fast with ConcurrentModificationException (chapter 07), even with one thread.
  2. CopyOnWriteArrayList.add copies the backing array and writes to the copy. The running loop keeps iterating the snapshot it started with, so it notifies audit and email only, and never throws.
  3. The list itself now has the new element: after: [audit, email, metrics].
  4. Every write copies the whole array, so it suits small lists that are read constantly and changed rarely: listener lists, routing tables, config. For a list with frequent writes, it's the wrong choice.
AdvancedBlockingQueue: producer and consumer
Pipeline.java
void main() throws InterruptedException {
    BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);    // holds at most 2

    Thread consumer = Thread.ofPlatform().start(() -> {
        try {
            while (true) {
                String order = queue.take();                    // waits while empty
                if (order.equals("DONE")) break;
                IO.println("shipped " + order);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    });

    for (int i = 1; i <= 5; i++) {
        queue.put("order-" + i);                                  // waits while full
    }
    queue.put("DONE");
    consumer.join();
    IO.println("all orders shipped");
}
Terminal
$ java Pipeline.java
shipped order-1
shipped order-2
shipped order-3
shipped order-4
shipped order-5
all orders shipped
What’s happening
  1. ArrayBlockingQueue<>(2) is a FIFO queue with room for two items. put blocks while it's full; take blocks while it's empty.
  2. main produces five orders. When the consumer falls behind, the third put waits until the consumer takes one: that's backpressure, built in, the same idea as a Node stream's highWaterMark.
  3. The consumer takes orders in FIFO order and prints them: shipped order-1 to shipped order-5. Only one thread prints, so the order is always the same.
  4. "DONE" is a poison pill: a special item that tells the consumer to stop. consumer.join() waits for it to finish, then all orders shipped.
  5. This is the shape inside every thread pool (workers take tasks from a queue) and the in-process version of a message queue like Kafka (chapter 17).

#Deadlocks and thread dumps

Added

A deadlock is two threads each holding a lock the other needs, waiting forever. The classic shape is a bank transfer: thread 1 locks account A then wants B; thread 2 locks B then wants A. Neither can move, nothing crashes, nothing is logged. The service just stops answering some requests while CPU stays at zero. Node can't deadlock this way (one thread, no locks), but it has the same family of bug in awaits that wait on each other.

The standard prevention is lock ordering: always take locks in one global order (for example by account id), so a cycle can't form. Other options: tryLock with a timeout and back off, hold fewer locks, or redesign so one thread owns the data (a queue, an actor). And the standard diagnosis is a thread dump: it lists every thread, its stack, the locks it holds and the lock it waits for, and HotSpot spots monitor deadlocks for you.

Deadlock.java
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;

void main() throws InterruptedException {
    Object accountA = new Object();
    Object accountB = new Object();
    var bothHoldOne = new CountDownLatch(2);

    Thread.ofPlatform().name("transfer-A-to-B").daemon()
            .start(() -> transfer(accountA, accountB, bothHoldOne));
    Thread.ofPlatform().name("transfer-B-to-A").daemon()
            .start(() -> transfer(accountB, accountA, bothHoldOne));

    var threads = ManagementFactory.getThreadMXBean();
    long[] ids = null;
    while (ids == null) {                          // poll until the JVM sees a deadlock
        Thread.sleep(100);
        ids = threads.findDeadlockedThreads();
    }
    Arrays.stream(threads.getThreadInfo(ids))
            .sorted(Comparator.comparing(ThreadInfo::getThreadName))
            .forEach(t -> IO.println(t.getThreadName() + " is " + t.getThreadState()
                    + ", waiting for a lock held by " + t.getLockOwnerName()));
}

void transfer(Object from, Object to, CountDownLatch bothHoldOne) {
    synchronized (from) {
        bothHoldOne.countDown();
        try { bothHoldOne.await(); } catch (InterruptedException e) { return; }
        synchronized (to) {                        // never gets here
            IO.println("transferred");
        }
    }
}
Terminal
$ java Deadlock.java
transfer-A-to-B is BLOCKED, waiting for a lock held by transfer-B-to-A
transfer-B-to-A is BLOCKED, waiting for a lock held by transfer-A-to-B
What’s happening
  1. Thread transfer-A-to-B locks accountA; thread transfer-B-to-A locks accountB. The latch makes each wait until both hold their first lock, so the deadlock happens every time instead of now and then (in production, it's timing-dependent, which is why it survives testing).
  2. Each then tries to lock the other account, which the other thread holds. Both block forever in state BLOCKED; transferred is never printed.
  3. main asks the JVM's ThreadMXBean (in the java.management module, hence the explicit import) every 100 ms: findDeadlockedThreads() returns the ids of threads stuck in a lock cycle, or null while there's none.
  4. For each it prints the name, the state and who owns the lock it wants: transfer-A-to-B is BLOCKED, waiting for a lock held by transfer-B-to-A, and the mirror image. Sorting by name keeps the output stable.
  5. The two threads are daemons, so the JVM can exit when main returns even though they're stuck. A real deadlock in a server has no such exit: the threads stay blocked until the process restarts.
  6. The fix is lock ordering: make transfer always lock the account with the smaller id first, and the cycle can't form (the exercises do this).
AdvancedA real thread dump with jcmd

In an incident you don't have a main that polls; you have a stuck process. jcmd (in the JDK's bin) lists running JVMs when run with no arguments, and jcmd <pid> Thread.print prints a thread dump of one of them. (jstack <pid> is the older tool that prints the same thing.) Here is a program that deadlocks and stays stuck, and a dump taken from it:

Stuck.java
void main() throws InterruptedException {
    Object accountA = new Object();
    Object accountB = new Object();
    var bothHoldOne = new CountDownLatch(2);
    var t1 = Thread.ofPlatform().name("transfer-A-to-B").start(() -> transfer(accountA, accountB, bothHoldOne));
    Thread.ofPlatform().name("transfer-B-to-A").start(() -> transfer(accountB, accountA, bothHoldOne));
    t1.join();                                     // waits forever
}

void transfer(Object from, Object to, CountDownLatch bothHoldOne) {
    synchronized (from) {
        bothHoldOne.countDown();
        try { bothHoldOne.await(); } catch (InterruptedException e) { return; }
        synchronized (to) {
            IO.println("transferred");
        }
    }
}
Terminal
$ java Stuck.java & sleep 5; jcmd $! Thread.print | grep -A 24 'Found one Java-level deadlock' | sed -E 's/0x[0-9a-f]+/0x…/g'; kill $!
Found one Java-level deadlock:
=============================
"transfer-A-to-B":
  waiting to lock monitor 0x… (object 0x…, a java.lang.Object),
  which is held by "transfer-B-to-A"

"transfer-B-to-A":
  waiting to lock monitor 0x… (object 0x…, a java.lang.Object),
  which is held by "transfer-A-to-B"

Java stack information for the threads listed above:
===================================================
"transfer-A-to-B":
	at Stuck.transfer(Stuck.java:15)
	- waiting to lock <0x…> (a java.lang.Object)
	- locked <0x…> (a java.lang.Object)
	at Stuck.lambda$main$0(Stuck.java:5)
	at Stuck$$Lambda/0x….run(Unknown Source)
	at java.lang.Thread.runWith(java.base@25.0.5.1/Thread.java:1487)
	at java.lang.Thread.run(java.base@25.0.5.1/Thread.java:1474)
"transfer-B-to-A":
	at Stuck.transfer(Stuck.java:15)
	- waiting to lock <0x…> (a java.lang.Object)
	- locked <0x…> (a java.lang.Object)
	at Stuck.lambda$main$1(Stuck.java:6)
What’s happening
  1. java Stuck.java & starts the program in the background, and $! is its process id. (java File.java compiles and runs in the same process, so that pid is the JVM.) In real life you'd run jcmd alone to find the pid of your service.
  2. After 5 seconds the program is deadlocked, and jcmd <pid> Thread.print dumps every thread. The full dump is long (GC threads, the JIT compiler threads, main waiting in join), so grep keeps the deadlock report HotSpot adds at the end, and sed hides the memory addresses (they change every run). kill $! stops the stuck program.
  3. The report names the cycle: transfer-A-to-B is "waiting to lock monitor … which is held by transfer-B-to-A", and the other way round.
  4. The stack part shows where: both threads are at Stuck.transfer(Stuck.java:15), the inner synchronized, each "waiting to lock" one object and having "locked" the other. Those file and line numbers are what you take back to the code.
  5. Thread.print -l adds the java.util.concurrent locks (such as ReentrantLocks) each thread holds, and ThreadMXBean.findDeadlockedThreads() from the previous example finds cycles through those locks as well as through monitors. Virtual threads are different: the traditional dump doesn't list them (JEP 444 chose not to extend it to millions of threads), so for them use jcmd <pid> Thread.dump_to_file -format=json <file>.

#Your turn: concurrency

Added
Your turn: fix the transfer deadlock

Rewrite transfer so two opposite transfers between the same accounts can never deadlock. Prove it by running 10,000 transfers in each direction at the same time and checking that the total money is unchanged.

Show answer
Bank.java
class Account {
    final int id;
    int balance;
    Account(int id, int balance) { this.id = id; this.balance = balance; }
}

void transfer(Account from, Account to, int amount) {
    Account first = from.id < to.id ? from : to;      // always lock the lower id first
    Account second = from.id < to.id ? to : from;
    synchronized (first) {
        synchronized (second) {
            from.balance -= amount;
            to.balance += amount;
        }
    }
}

void main() throws InterruptedException {
    var a = new Account(1, 1_000);
    var b = new Account(2, 1_000);
    try (var pool = Executors.newFixedThreadPool(8)) {
        for (int i = 0; i < 10_000; i++) {
            pool.submit(() -> transfer(a, b, 1));
            pool.submit(() -> transfer(b, a, 1));
        }
    }
    synchronized (a) {
        synchronized (b) {
            IO.println("total: " + (a.balance + b.balance));
        }
    }
}
Terminal
$ java Bank.java
total: 2000
What’s happening
  1. The deadlock needed two threads taking the same two locks in opposite orders. Here both directions lock the account with the lower id first, so whoever gets a first also gets b, and the other thread waits for both; no cycle can form.
  2. Holding both locks while changing both balances also makes the transfer atomic: no other thread ever sees money that has left one account but not arrived in the other.
  3. 20,000 transfers run on 8 threads; try-with-resources waits for all of them. The program finishes (no deadlock) and prints total: 2000, the money we started with.
  4. The final read also takes both locks, so main is guaranteed to see the last writes (happens-before through the monitors; the executor's close() gives the same guarantee).
Your turn: limit concurrency with a Semaphore

You have 50 tasks to run on virtual threads, but the service they call accepts at most 5 calls at a time. Use a Semaphore (not a pool of 5) and prove that no more than 5 tasks were ever inside the call at once.

Show answer
Limit.java
void main() {
    var permits = new Semaphore(5);
    var inside = new AtomicInteger();
    var maxInside = new AtomicInteger();

    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
        for (int i = 0; i < 50; i++) {
            executor.submit(() -> {
                permits.acquire();                       // wait for one of 5 permits
                try {
                    int now = inside.incrementAndGet();
                    maxInside.accumulateAndGet(now, Math::max);
                    Thread.sleep(50);                    // the call to the fragile service
                    inside.decrementAndGet();
                } finally {
                    permits.release();
                }
                return null;
            });
        }
    }
    IO.println("never more than 5 at once: " + (maxInside.get() <= 5));
    IO.println("reached 5 at once: " + (maxInside.get() == 5));
}
Terminal
$ java Limit.java
never more than 5 at once: true
reached 5 at once: true
What’s happening
  1. All 50 tasks start on their own virtual threads at once: cheap, so there's no reason to pool them.
  2. Semaphore(5) holds 5 permits. acquire() takes one, or blocks (unmounting the virtual thread) until one is free; release() in finally gives it back even if the call fails.
  3. Inside the guarded section, inside counts current callers and accumulateAndGet(now, Math::max) atomically keeps the highest count seen.
  4. The maximum never exceeds 5 (true), and with 50 tasks each holding a permit for 50 ms, all 5 permits are in use at once (true). This is JEP 444's advice in code: limit concurrency with a semaphore, not with a pool of virtual threads.
Your turn: fan out with CompletableFuture

Three price services each take about a second. Ask all three at once on virtual threads, wait for all of them with allOf, and print the cheapest price. The whole thing should take well under the 3 seconds that asking them one by one would.

Show answer
Cheapest.java
int quote(String shop, int cents) {
    try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); }
    return cents;
}

void main() {
    try (var io = Executors.newVirtualThreadPerTaskExecutor()) {
        long start = System.nanoTime();
        var quotes = List.of(
                CompletableFuture.supplyAsync(() -> quote("north", 5299), io),
                CompletableFuture.supplyAsync(() -> quote("east", 4899), io),
                CompletableFuture.supplyAsync(() -> quote("west", 5099), io));

        CompletableFuture.allOf(quotes.toArray(new CompletableFuture[0])).join();
        int cheapest = quotes.stream().mapToInt(CompletableFuture::join).min().orElseThrow();

        IO.println("cheapest: " + cheapest);
        IO.println("asked in parallel (under 2,000 ms): " + ((System.nanoTime() - start) / 1_000_000 < 2000));
    }
}
Terminal
$ java Cheapest.java
cheapest: 4899
asked in parallel (under 2,000 ms): true
What’s happening
  1. Each supplyAsync(…, io) starts its call immediately on a virtual thread, so all three are waiting at the same time.
  2. allOf takes an array (hence toArray(new CompletableFuture[0])) and returns a CompletableFuture<Void> that completes when all three have: Java's Promise.all, except that it doesn't hand you the values.
  3. After allOf(…).join(), each join() returns immediately with its value, and the stream picks the minimum: cheapest: 4899.
  4. The three one-second waits overlapped, so the total is about one second: true. With plain blocking calls on virtual threads, invokeAll on the same executor would work just as well.

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.