Workbench / Volume 3 Exercises: The Backend
V3·38
Concurrency
Exercises for Volume 3, chapter 38: why backends are concurrent; concurrency versus parallelism and the concurrency models; threads, Runnable and Callable, executors, Future and CompletableFuture; the Java memory model and happens-before; synchronized, volatile, atomics, explicit locks and coordination primitives; ForkJoinPool, thread-per-request versus non-blocking, virtual threads and structured concurrency; async/await, goroutines and channels; deadlock, livelock, starvation, contention and false sharing; and testing and choosing an approach. 10 theory questions, 10 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
The four sets and the locking work as before. The code is Java 21, with structured concurrency and scoped values run as JDK 21 previews (--enable-preview). Go 1.24 (with its race detector) and Rust 1.97 are there for comparison. The machine has 2 cores, which affects some results, and every quoted output is real.
Seven of the outputs catch experienced developers:
- P1. 4 threads × 1,000,000 unsynchronised
++, started together, gave 3,790,229. Withvolatile, the result was still wrong: 3,821,547. - P2. A
CompletableFuturethat threw and was never joined printed nothing: the failure was invisible. - P2. On this 2-core machine the common pool's parallelism was 1, so
supplyAsyncran on a plainThread-N(a new thread per task), not a fork-join worker. - P3.
submit()swallowed an exception untilget()was called. - P3. A pool with 1 thread and a queue of 2 rejected 7 of 10 quick submissions.
- P4. A
ThreadLocalset by one task was still visible to the next task on the same pooled thread. - P5. A task that swallowed
InterruptedExceptiondidn't stop aftershutdownNow(). - P8. Two threads incrementing two
volatilefields in one object took 2,618 ms. Two padded objects took 510 ms: false sharing.
The chapter's lab measured these, and the exercises build on them rather than repeat them:
- a plain
booleanstop flag never seen by another thread (volatilefixed it); - a deadlock found by
ThreadMXBean; - 10,000 waiting tasks: 5,289 ms on 200 platform threads against 158 ms on virtual threads;
- virtual threads pinned by
synchronizedon JDK 21 (2,581 ms) and fixed in JDK 25 (149 ms); - check-then-act building a value 8 times against
computeIfAbsent's once.
Coverage map.
| Chapter component | Exercises |
|---|---|
| why backends are concurrent; concurrency vs parallelism; models | T1 |
| threads, Runnable, Callable; executors | T2, P3 |
| Future and CompletableFuture | T3, P2 |
| memory model; happens-before; other languages | T4, P1 |
| synchronized; volatile; atomics and CAS | T5, P1 |
| explicit locks; semaphores, latches, barriers, phasers | T6, P6 |
| ForkJoinPool and work stealing | T7, P2 |
| thread-per-request vs non-blocking; virtual threads | T7, P6 |
| structured concurrency; scoped values | T8, P7 |
| async/await elsewhere; goroutines and channels | T9, P9 |
| deadlock, livelock, starvation | T10, P10 |
| contention; false sharing | T5, P8 |
| interruption and cancellation; ThreadLocal | T2, P4, P5 |
| tools and testing; choosing an approach | T10, P10 |
Theory
T1. Why backends are concurrent, and the models
- A TiffinBox API instance serves 300 requests per second. Each request spends 5 ms on CPU and 60 ms waiting on the database and the kitchen API. Using Little's law (concurrency = throughput × latency), how many requests are in flight at once? How many threads does a thread-per-request server need? What happens with a pool of 50?
- Define concurrency (dealing with many things at once: structure) and parallelism (doing many things at once: execution). Give a backend example of concurrency without parallelism on 1 core, and of parallelism without concurrency in the program's structure (a parallel stream over one batch).
- Compare the concurrency models: - shared memory with locks (Java, C++); - message passing and actors (Erlang, Akka); - CSP channels (Go); - event loops (Node.js, Volume 2); - async/await over futures (C#, JavaScript, Rust, Python); - software transactional memory (Clojure, Haskell).
What does each make easy, and what does each make hard?
T2. Threads, tasks and executors
- Compare
ThreadwithRunnableandCallable, and explain why application code should submit tasks to executors rather than create threads. Cover what anExecutorServicemanages (threads, queue, rejection, lifecycle) and whynewFixedThreadPool's unboundedLinkedBlockingQueueis a production risk. - Two P3 results:
-
submit()swallowed an exception untilget(): "ExecutionException: boom in submit", printed nowhere before that; - aThreadPoolExecutorwith 1 thread, a queue of 2 andAbortPolicyaccepted 3 and rejected 7, whileCallerRunsPolicyran 4 of 10 on the submitting thread and slowed it to 201 ms.
Explain both, and how to size and configure pools for CPU-bound and I/O-bound work.
3. Explain interruption and cancellation. P5 found that a task swallowing InterruptedException didn't stop within 1 second of shutdownNow(), while one that restored the interrupt flag and returned stopped. Then cover ThreadLocal on pooled threads: P4's next task saw customer=asha. Give the rules for each.
T3. Future and CompletableFuture
- Compare
Future(blockingget, no composition) withCompletableFuture: -thenApply,thenCompose,thenCombine,allOf/anyOf; -exceptionally,handle,whenComplete; - the…Asyncvariants and their executors; -orTimeoutandcompleteOnTimeout.
In P2, completeOnTimeout(300 ms) on a 2-second call returned "eta unknown" after 300 ms, and orTimeout produced TimeoutException. Does either stop the underlying 2-second work?
2. P2's two surprises:
- a failed future nobody joined printed nothing (isCompletedExceptionally was true);
- on this 2-core machine supplyAsync ran on Thread-N, because the common pool's parallelism was 1 and CompletableFuture falls back to a new thread per task when parallelism is below 2.
Why are both production hazards, and what's the rule for executors with CompletableFuture?
3. Write the TiffinBox "order details" endpoint that fetches the order (database), the ETA (maps API) and the kitchen status (kitchen API) concurrently, with a 300 ms budget for optional parts, and fails fast if the order lookup fails. Then compare the CompletableFuture version with a structured concurrency version (T8).
T4. The memory model and happens-before
- The lab's plain
booleanstop flag was never seen by the looping thread (after 2 s: still running), whilevolatileworked. P1 showed that evenvolatile int ++loses updates (3,821,547 of 4,000,000). Explain the two separate problems, visibility and atomicity, and which tools solve which. - Define happens-before and list the edges Java guarantees:
- program order;
- monitor unlock to a later lock;
- volatile write to a later read;
-
Thread.start; -Thread.join; - executor submission to task execution; -Futurecompletion toget; - concurrent collection put to get; - final-field freeze at the end of a constructor.
Use them to explain why ConcurrentHashMap and executors "just work" for publishing objects.
3. Explain safe publication and the broken double-checked locking idiom (before Java 5, and without volatile), and compare memory models: C/C++'s memory_order, Go's ("don't be clever": the race detector found 2 races in P9 and the result was 327,652 of 400,000), and Rust (data races are compile errors: P9's Rc "cannot be sent between threads safely").
T5. synchronized, volatile, atomics and contention
- Explain
synchronized: - intrinsic monitors and reentrancy; -wait/notify(and why to prefer higher-level tools); - the cost when uncontended (cheap) against contended (parking and context switches); - P1's 305 ms against 80 ms forAtomicIntegerand 62 ms forLongAdder, with 4 threads on 2 cores. - Explain compare-and-swap (CAS):
AtomicInteger,AtomicReference, the ABA problem,LongAdder's striped cells, andVarHandle. When does CAS beat locks, and when does it spin badly? - P8's false sharing result: two threads updating adjacent
volatilefields took 2,618 ms, against 510 ms for separate padded objects. Explain cache lines (64 bytes), the MESI coherence protocol and@Contended, and when false sharing matters in backend code (hot counters and metrics, queue head and tail indexes).
T6. Explicit locks and coordination primitives
- Compare
ReentrantLockwithsynchronized:tryLockwith timeout,lockInterruptibly, fairness, severalConditions, and (before JDK 24) not pinning virtual threads (the lab's 2,581 ms against 149 ms). Then coverReadWriteLockandStampedLock(optimistic reads). When is each justified? - Give a TiffinBox use case for each coordination primitive:
-
Semaphore: P6 limited 1,000 virtual threads to 20 concurrent calls, finishing in 1,029 ms; -CountDownLatch: P1's start gate; -CyclicBarrier; -Phaser; -Exchanger; -BlockingQueuefor producer and consumer. - Locks across processes. Why doesn't a Java lock protect anything once TiffinBox runs 3 instances? Name the alternatives: database row locks and
SELECT … FOR UPDATE, unique constraints, optimistic version columns, advisory locks, and Redis-based locks with their caveats (ch49, ch53).
T7. ForkJoinPool, thread-per-request, non-blocking and virtual threads
- Explain
ForkJoinPooland work stealing (per-worker deques, LIFO local work, FIFO stealing), which work it suits (recursive divide and conquer, parallel streams), and the common pool's sizing (P2: parallelism 1 on 2 cores). - Compare thread-per-request (Tomcat, blocking JDBC: simple, but each waiting request holds a platform thread) with non-blocking servers (Netty, WebFlux, Node.js: few threads, but callbacks or reactive types everywhere). Why did reactive programming spread in 2015–2022, and what did virtual threads (the lab: 5,289 ms against 158 ms for 10,000 waiting tasks) change?
- Virtual threads: how do they work (continuations mounted on carrier threads, unmounting when blocked)? What are their pitfalls?
- pinning: the lab's 2,581 ms on JDK 21, fixed in 24+; native calls and class initialisers still pin;
- they don't speed up CPU-bound work;
- unbounded concurrency hitting connection pools (P6's semaphore);
-
ThreadLocalcosts (P4); - never pooling them.
T8. Structured concurrency and scoped values
- Explain structured concurrency: subtasks' lifetimes are bounded by a lexical scope, errors propagate, and cancellation is automatic. P7 used JDK 21's preview
StructuredTaskScope.ShutdownOnFailure. The "eta" subtask failed at 100 ms, the "menu" subtask was interrupted ("menu cancelled (interrupted) after the sibling failed"), and the scope failed after 113 ms instead of 1,000. Compare this with P2'sCompletableFuture, where siblings keep running. - Explain scoped values: immutable, bounded per-scope data that is inherited by forked subtasks. P7 printed
ScopedValue inside scope: req-42andbound after run? false. Compare them withThreadLocal(P4's leak). Which TiffinBox context belongs in them: request id, tenant, security principal? - The APIs have been evolving. Structured concurrency was still a preview in JDK 25, reshaped around
StructuredTaskScope.open(Joiner); scoped values became final in JDK 25. How should a team adopt preview features: never in production, behind wrappers, or only after they're final?
T9. Async/await elsewhere, goroutines and channels
- Compare async models:
- JavaScript's single-threaded
async/await(Volume 2); - C#'sasync/awaitover a thread pool; - Rust'sasync(futures do nothing until polled, executors like Tokio,Sendbounds); - Python'sasyncio, plus the GIL and free-threading; - Kotlin coroutines (structured, suspend functions).
What is "function colouring", and how do Java's virtual threads and Go's goroutines avoid it?
2. Go's goroutines and channels. P9 showed:
- a worker pool over a jobs channel summing to 30;
- select with time.After timing out on an unbuffered channel;
- the race detector catching an unsynchronised counter (327,652 of 400,000, "Found 2 data race(s)").
Explain unbuffered against buffered channels, closing, range over channels, goroutine leaks, context.Context cancellation, and errgroup.
3. Translate a Go pattern (fan-out to 3 workers, collect results, cancel all on the first error) into Java with virtual threads and a structured scope, and say which language makes it simpler.
T10. Failure modes, tools, testing and choosing an approach
- Define deadlock, livelock and starvation. The lab found a deadlock between two transfers with
ThreadMXBean("transfer A→B waits for a lock held by transfer B→A"). Give the four Coffman conditions and a prevention technique for each, a TiffinBox example of livelock (two retrying services backing off in lockstep), and one of starvation (an unfair lock, or a thread pool saturated by slow tasks). - Tools and testing:
- thread dumps (
jcmd Thread.print,jstack); - JFR events (lock contention, virtual thread pinning); - jcstress for memory-model tests; - stress tests with start gates (P1's latch); - Go's-race; - deterministic testing approaches (Lincheck, controlled schedulers).
Why do concurrency bugs pass tests? 3. Choose an approach for a TiffinBox Java 21+ backend: - request handling; - fan-out to downstream services; - CPU-heavy reports; - background jobs; - in-memory shared state; - cross-instance coordination.
Justify each choice.
Programming exercises
P1. Visibility, atomicity and the cost of correctness
Start 4 threads together with a CountDownLatch and have each increment a shared counter 1,000,000 times, using:
- a plain int;
- a volatile int;
- synchronized;
- AtomicInteger;
- LongAdder.
Report the final values and the times. Then explain why an earlier version, which started the threads one after another without a latch, printed the correct 4,000,000 for a plain int.
P2. CompletableFuture: errors, timeouts and executors
Show these behaviours:
- a failed future nobody joins printing nothing;
- join wrapping the failure in CompletionException;
- an exceptionally fallback;
- completeOnTimeout against orTimeout;
- which thread supplyAsync uses on this machine, and the common pool's parallelism.
Then show that the timed-out 2-second task keeps running, and fix the "order details" fan-out (T3) with an explicit executor, client-side timeouts and logging of every failure.
P3. Executors: lost exceptions and rejection
Show:
- submit() hiding an exception until get(), and execute() printing it;
- a bounded ThreadPoolExecutor (1 thread, queue 2) with AbortPolicy against CallerRunsPolicy under 10 quick submissions;
- newFixedThreadPool's unbounded queue growing (submit 100,000 slow tasks and print getQueue().size()).
Then build TiffinBox's notification pool: bounded, named threads, a rejection policy that sheds load with a metric, and a shutdown sequence.
P4. ThreadLocal leaks and context propagation
Show a ThreadLocal set by one task visible to the next task on a pooled thread. Fix it with try/finally remove(). Then propagate a request id from a request thread into async tasks in three ways:
- explicit parameters;
- a wrapping executor that copies MDC context;
- (JDK 21 preview) a ScopedValue.
P5. Interruption and cancellation
Write two tasks that sleep in a loop: one swallows InterruptedException, the other restores the flag and returns. Show which one stops after shutdownNow(). Then make a CPU-bound loop cancellable by checking Thread.interrupted(), and make a blocking HTTP call cancellable by using a client timeout. Write the team rule.
P6. Virtual threads with bounded resources
Run 1,000 virtual-thread tasks that each call a simulated kitchen API taking 20 ms, limited to 20 concurrent calls with a Semaphore. Measure the maximum concurrency observed and the total time. Then:
- replace the semaphore with a connection pool of 20 (a BlockingQueue of tokens) and compare;
- show what happens without any limit if the API rate-limits at 20 concurrent (simulate 429s);
- add a timeout on tryAcquire.
P7. Structured concurrency (preview)
With JDK 21 and --enable-preview, implement order details with StructuredTaskScope.ShutdownOnFailure. One subtask fails at 100 ms while another would take 1,000 ms. Show that the sibling is interrupted and the scope fails in about 100 ms. Then implement "first successful quote from three kitchens" with ShutdownOnSuccess, and port both to the JDK 25 preview API shape (StructuredTaskScope.open(Joiner…)) in comments, noting the differences.
P8. Contention and false sharing
Measure two threads incrementing adjacent volatile fields in one object against fields in separate padded objects. Then compare LongAdder against AtomicLong with 2, 4 and 8 threads, and a single synchronized counter against per-thread counters merged at the end. Explain the results with cache lines.
P9. Goroutines, channels and the race detector; Rust's guarantees
In Go:
- run 4 goroutines incrementing a shared counter under go run -race;
- build a worker pool with channels;
- time out with select and time.After;
- fix the counter with sync/atomic and with a mutex;
- write an errgroup fan-out that cancels on the first error.
In Rust:
- try to share an Rc across threads;
- fix it with Arc<Mutex<…>>.
P10. Deadlock, detection and prevention
Recreate the lab's transfer deadlock, detect it with ThreadMXBean.findDeadlockedThreads() and with jcmd Thread.print, then fix it three ways:
- a global lock order;
- tryLock with a timeout and backoff;
- no nested locks: a single "ledger" actor thread that processes transfers from a queue.
Finally, write the database version: two transactions updating rows in opposite order, which the database detects and aborts.
Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–38)
C1. A concurrent order-details aggregator
Build the TiffinBox order-details service. It fetches the order, ETA, kitchen status and recommendations concurrently on virtual threads, with: - per-dependency semaphores and client timeouts; - fallbacks for optional parts; - fail-fast for the required order lookup, with sibling cancellation (structured scope or manual cancellation); - request-id propagation; - metrics (latency per dependency, timeouts, rejections).
Load test it with simulated slow dependencies and show the p50, p95 and p99 latency staying within budget.
Combines: Volume 1's networking and latency, Volume 2's frontend loading states (ch19, ch27), ch37's functional core, and this chapter.
C2. A safe in-memory kitchen state store
Implement the kitchen dashboard's in-memory state: order statuses updated by event consumers on several threads, and read by thousands of dashboard requests. Compare three designs under load:
- a synchronized map;
- a ConcurrentHashMap with atomic updates;
- a single-writer thread publishing immutable snapshots through an AtomicReference.
Measure read and write latency and throughput, check consistency (no torn reads across related fields), and choose one.
Combines: Volume 2's dashboard state model (ch25), ch35's ConcurrentHashMap and snapshots, ch37's immutability, and this chapter.
C3. Cross-language concurrency comparison
Implement "fetch quotes from 5 kitchen APIs concurrently, 300 ms deadline, cancel the rest on the first error, return the 3 cheapest" in:
- Java (virtual threads plus a structured scope, or CompletableFuture);
- Go (errgroup plus context);
- TypeScript and Node (Promise.allSettled plus AbortController, Volume 2);
- Rust (Tokio JoinSet plus timeout).
Compare the code length, how cancellation reaches the HTTP calls, error handling, and the behaviour when an API hangs.
Combines: Volume 2's frontend async and fetch cancellation (ch19), ch33's language comparison, and this chapter's models.
What the chapter leaves out
Lock-free data structures and the Disruptor
Beyond atomics, there are lock-free queues (ConcurrentLinkedQueue, Michael–Scott), JCTools' specialised SPSC and MPSC queues, and the LMAX Disruptor (a ring buffer with padded sequences, used for very low-latency pipelines such as trading and logging in Log4j 2's async loggers). They avoid locks and false sharing (P8). Most backends never need them directly, but you'll find them inside libraries and need to recognise them when tuning.
Reactive streams in depth
Project Reactor and RxJava model asynchronous sequences with backpressure, schedulers and operators (flatMap with concurrency limits, retryWhen, timeout). WebFlux (ch48) is built on them. Their failure modes are blocking inside reactive chains (use BlockHound to detect it), lost context (Reactor Context), and hard-to-read stack traces (checkpoints, Hooks.onOperatorDebug). With virtual threads, many teams no longer need them, but streaming and backpressure-heavy cases still benefit.
Actor frameworks and the Java ecosystem
Akka (now under the BSL licence; Apache Pekko is the open fork), Vert.x's verticles and event bus, and Orleans-style virtual actors (Microsoft) offer message-passing models on or near the JVM. They provide location transparency and supervision, at the cost of a different programming model. They suit stateful, highly concurrent domains (game servers, IoT, chat), and are rarely needed for CRUD-style backends.
Time, clocks and concurrency
System.currentTimeMillis() can jump (NTP adjustments), so durations should use System.nanoTime(). Timeouts must be monotonic. Distributed systems can't rely on clocks for ordering, which is why Lamport and vector clocks and hybrid logical clocks exist (Volume 4). In tests, inject a Clock and control time instead of sleeping, so concurrent tests become deterministic and fast.
Formal reasoning: linearizability and TLA+
Linearizability (each operation appears to happen atomically at some point between its start and its end) is the correctness criterion for concurrent objects. Lincheck tests it on the JVM. For distributed protocols and tricky concurrency (leader election, payment workflows), TLA+ and similar model checkers explore every interleaving and find bugs that tests can't. Engineers at AWS and elsewhere use them for critical designs. They're worth learning for senior work on core systems.
Senior exercises
S1. The team's concurrency rulebook
Write a one-page rulebook covering:
- defaults (virtual threads for request handling, explicit executors);
- the shared-state policy (immutable snapshots, ConcurrentHashMap with atomic methods);
- bounded queues and rejection;
- timeouts everywhere;
- interruption and ThreadLocal rules;
- no parallel() in request paths;
- lock ordering;
- cross-instance coordination through the database;
- testing and tooling requirements.
Tie each rule to an output from this chapter.
S2. Review a concurrency-heavy pull request
A PR adds a "kitchen sync" feature with:
- a static HashMap<KitchenId, Status> updated by a scheduled task and read by requests;
- a boolean running flag checked in the task's loop;
- CompletableFuture.supplyAsync(() -> kitchenApi.fetch(k)) for 300 kitchens with no executor and no timeout;
- Executors.newFixedThreadPool(50) created per sync run and never shut down;
- synchronized around the HTTP call on JDK 21 with virtual threads enabled;
- catch (InterruptedException e) {} in a retry sleep.
Write the review.
S3. Decide whether to migrate a WebFlux service to virtual threads
TiffinBox's notification service is written with Spring WebFlux and Reactor (2019). It's hard to debug, new hires struggle with it, and some libraries in it block (BlockHound reports them). The service handles 2,000 requests per second, mostly waiting on a push provider. Should it move to Spring MVC on virtual threads? Write the decision, covering risks, a migration plan and how you'll measure success.
S4. Teach the memory model with three outputs
Prepare a 15-minute session using:
- the lab's plain stop flag that never stopped;
- P1's volatile counter losing updates;
- P8's false sharing (2,618 ms against 510 ms).
Use them to teach visibility, atomicity and hardware reality. End with three rules.
S5. Incident analysis: a thread-pool starvation outage
During a festival sale, TiffinBox's API stopped responding for 12 minutes. A thread dump showed all 200 Tomcat threads blocked in KitchenApiClient.get (no read timeout). The kitchen API had slowed to 30 s responses. Health checks timed out, the load balancer removed instances one by one, and the remaining instances got more traffic. Write the post-incident analysis: timeline, root causes, contributing factors, fixes and verification.