Lesson 5 of 9 · 24m
Structured Concurrency and Scoped Values Without Cargo-Culting Them
Shape concurrent work as a lifetime-bound tree, cancel correctly, and understand what scoped values replace before adopting preview APIs.
The worst concurrency bugs I have inherited were not races. They were abandoned tasks: a request timed out, the thread pool kept working, the database kept burning, and three days later someone discovered an invoice had been emailed twice. Structured concurrency exists to make task lifetime match business lifetime. Virtual threads supply the mechanics; structure supplies the discipline.
A request is a tree, not a bag of futures
When handling a request, child operations should not outlive the parent by accident. If pricing, inventory, and fraud checks are all required, failure or cancellation should propagate as one unit.
The old implementation often submits all four to an executor and then manages Future objects by hand. The modern goal is a single lexical scope: enter together, fork children, join them, propagate failure, exit together.
The Java 21 caveat
StructuredTaskScope exists as a preview API in the Java 21 era, not as a stable no-caveat mainstream API. Exact details have evolved across JDK releases. Read the Javadoc for the JDK you deploy and compile preview code explicitly with preview features enabled.
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Subtask<Customer> customer = scope.fork(() -> customers.load(customerId));
Subtask<Inventory> inventory = scope.fork(() -> inventoryService.check(items));
scope.join().throwIfFailed();
return new Quote(customer.resultNow(), inventory.resultNow());
}The shape matters more than the version-specific class name: child lifetimes are bounded, failure shuts down siblings, and nobody forgets a thread because a branch returned early.
Cancellation is a contract
A virtual thread cancellation still relies on interruption. If your blocking call ignores interrupts, structure cannot rescue it. JDBC drivers, HTTP clients, queues, and native libraries differ in how promptly they respond.
Do not catch InterruptedException, log it, and continue as if nothing happened. Restore the interrupt or propagate it. Cancellation is part of correctness under timeouts.
Scoped values solve a narrower problem than people expect
ThreadLocal couples context to a thread. That was tolerable when one request mapped cleanly to one pooled platform thread. In virtual-thread and nested-concurrency code, implicit context becomes awkward and inheritance can be surprising.
Scoped values are designed for immutable context with a bounded lifetime:
private static final ScopedValue<TraceContext> TRACE = ScopedValue.newInstance();
ScopedValue.where(TRACE, traceContext).run(() -> handleRequest());Inside that dynamic scope, TRACE.get() sees the value. Outside it, the context is absent. This is cleaner for trace IDs, tenants, and security context than passing fifteen parameters — but it is still implicit context. Use it for cross-cutting metadata, not for hiding core dependencies.
Do not adopt structure as decoration
If the codebase already has mature reactive pipelines, do not rewrite them because virtual threads are fashionable. If it has simple synchronous service code, virtual threads plus explicit lifetime boundaries can delete an enormous amount of accidental complexity. The right modernization target is the concurrency model developers can reason about during a 3 a.m. incident.
Field notes
- Preview APIs require exact JDK-version checking; do not copy examples across releases blindly.
- Structure helps only when child work honors interruption.
- A timeout on the outer request does not automatically mean downstream calls have sane individual deadlines.
- Scoped values are immutable context, not a replacement for dependency injection.
- Test cancellation by slowing one branch and asserting siblings stop and resources close.
Was this lesson helpful?