Lesson · Virtual Threads & Structured Concurrency
Structured concurrency: subtask lifetimes with a fence
16 min readStructured Concurrency
Submitting to an executor returns a Future, not a relationship: nothing ties a subtask to the method that started it, so one failure leaves the other tasks running and cancellation is manual. StructuredTaskScope turns a group of subtasks into a block. Fork inside, join as a unit, and a fail-fast policy can cancel the survivors before the block exits, with every thread it started finished by the time it does. The API is in preview and still moving, and this lesson says so at each step.
The problem: submit() returns a value, not a relationship
Here is the fan-out everyone writes: two independent calls, submitted to an executor, joined with get(). It reads well and it is correct on the happy path.
The lifetimes, though, are not connected. If findUser() throws, the Future carries the failure while fetchOrder() keeps running in its own thread, because nothing told it to stop. If the calling thread is interrupted, the interruption stays with the caller and both subtasks carry on. If findUser() is slow and fetchOrder() has already failed, the code still blocks on the slow one before it can even look at the failure.
That list is the whole motivation for structured concurrency, and it comes to one sentence: the task knows its subtasks, the code does not. Observability pays the same price, because a thread dump shows three unrelated stacks with no hint of which belongs to what.
Response handle() throws Exception { Future<String> user = pool.submit(() -> findUser()); Future<Integer> order = pool.submit(() -> fetchOrder()); // If fetchOrder() fails first, this line still waits for findUser(), // and nothing cancels it: the link between the two exists only here. return new Response(user.get(), order.get()); }
Nothing in submit() binds a subtask to the method that started it; the relationship is a comment at best.
The shape: a scope that cannot close before its children leave
StructuredTaskScope makes the relationship part of the syntax. Open a scope, fork subtasks into it, join them as a unit, then read the results inside the block. The scope is AutoCloseable, so the try-with-resources statement is the lifetime: the block cannot exit while a thread it started is still running.
Four members do the work: a constructor that opens the scope and captures the current scoped-value bindings, fork(Callable) to start a subtask, join() to wait for the group, and close() from the try-with-resources. Subtasks run on virtual threads by default, one per fork.
fork returns a Subtask, which is also a Supplier, so the result is read after the join and never blocks. join().throwIfFailed() is the all-or-nothing line: if any subtask failed, the failure surfaces here, at the block that owns the work.
Response handle() throws Exception { // The block is the lifetime: nothing forked here can outlive it. try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { Supplier<String> user = scope.fork(() -> findUser()); Supplier<Integer> order = scope.fork(() -> fetchOrder()); scope.join() // wait for the group, or for a failure to shut it down .throwIfFailed(); // surface the first failure at the block that owns the work return new Response(user.get(), order.get()); } }
| Call | What it does | What it guarantees |
|---|---|---|
| the constructor | opens a scope owned by the calling thread; the zero-arg form creates virtual threads | the bindings in effect are captured for the threads it will start |
| fork(task) | starts a thread for the task and returns a Subtask | a thread started in this scope can never outlive the scope |
| join() | waits until all subtasks finish, the policy shuts the scope down, or the owner is interrupted | returns the scope; results are read only after it |
| close() via try-with-resources | shuts the scope down if that has not happened, then waits | the block cannot exit with a forked thread still running |
A scope cannot close before its children leave: structure is the cancellation policy.
A scope is a box with no early exit
fork inside · join as a unit · close waits
subtask A · findUser
running on its own virtual thread; interruption expected
subtask B · fetchOrder
the first failure is captured here, then the scope shuts down
owner thread
join() → throwIfFailed() → read results
join stops early when the scope shuts down; the results are read only after it returns.
close() waits for every thread the scope started
exiting with a forked thread still running is not possible; an interrupt-ignoring task only delays the exit.
ShutdownOnSuccess · the same box, the other policy
Both attempts are forked. The first success is captured, the scope shuts down, and the slower attempt is interrupted; join().result() returns the winner. If every attempt fails, result() throws an ExecutionException with one failure as the cause.
What happens when one subtask fails
ShutdownOnFailure implements one policy: the first subtask to fail is captured, and the scope is shut down. Shutdown interrupts every unfinished thread, prevents new forks from starting, and wakes the owner if it is waiting in join(). A subtask forked after that does not run at all, and reports the state UNAVAILABLE.
join() returns as soon as the scope is shut down, which is the part people miss: it can return before the interrupted tasks have finished dying. The waiting is completed by close(), which always waits for every thread the scope started. Two members, two jobs: join is the decision point, close makes sure nothing is still running.
throwIfFailed() then throws an ExecutionException whose cause is the exception of the first subtask to fail. The remaining cancellation is interruption, so it is cooperative: a subtask that swallows InterruptedException, or blocks somewhere uninterruptible, delays the close of the block until it decides to stop.
| Subtask state | What it means | Reading the result |
|---|---|---|
| SUCCESS | the task completed normally before the scope shut down | get() returns the value; before the join it throws IllegalStateException |
| FAILED | the task threw before the scope shut down | exception() returns the throwable; get() throws IllegalStateException |
| UNAVAILABLE | cancelled: still running at shutdown, completed after it, or forked after it | neither get() nor exception() is legal; there is no result to read |
Cancellation is interruption: the scope can close the door, but the subtask has to walk through it.
StructuredTaskScope · two policies, one block
not forked yet
not forked yet
owner thread
opens the scope at the top of the try-with-resources block
handle() opens a ShutdownOnFailure scope. The owner is this thread, and the zero-arg constructor plans to run every subtask on its own virtual thread.
Two policies cover the two common shapes
ShutdownOnFailure is the invoke-all shape: every result is required, so one failure makes the survivors pointless. ShutdownOnSuccess is the invoke-any shape: the first success is the answer, so the slower attempts are cancelled the moment one lands. Hedged reads, mirror races and redundant services are the canonical fit for the second one.
Both are subclasses of the same scope and differ in the method they add. throwIfFailed() surfaces the first failure; result() returns the first successful value, and throws an ExecutionException with a failure as the cause when nobody succeeded.
Deadlines come from joinUntil(Instant), which throws a TimeoutException when the deadline passes; the try-with-resources then shuts the scope down and cancels whatever is left. Either way, the subtasks still have to react to interruption: the API can only deliver the cancellations, not enforce them.
| Policy | Shuts the scope down when | You call | Outcome when it goes wrong |
|---|---|---|---|
| ShutdownOnFailure | the first subtask fails | join().throwIfFailed() | ExecutionException with the first failure as its cause; exception() exposes it as an Optional |
| ShutdownOnSuccess | the first subtask succeeds | join().result() | ExecutionException when every subtask failed; TimeoutException when the deadline passed |
| your own subclass | your handleComplete() decides | whatever you define after join() | your policy, your report: the hook sees every completion before shutdown |
Failure policy cancels the survivors on the first failure; success policy cancels them on the first success; both keep the block as the unit of work.
Preview status, and the shape that moved
StructuredTaskScope is a preview API and has been evolving through several previews since JDK 21. Using it needs --enable-preview at compile and run time, and preview APIs can change between releases, so the JDK you build against is part of the design decision.
The shape in this lesson is the documented one across JDK 21 to 24: public constructors plus the two policy subclasses. JDK 25's fifth preview replaces the constructors with static open methods and moves the policy into a Joiner object, turning the scope into a sealed interface. Different surface, same guarantees: a lexical lifetime, fail-fast cancellation, and a tree of tasks.
What has not moved is the intent. The scope is deliberately not an ExecutorService, and it does not implement that interface, because ExecutorService exists for free-form submission and the scope enforces structure at run time. Fork from a thread outside the tree, or leave the block without joining, and the API throws instead of guessing.
- Preview churn is expected: treat the snippet here as the documented 21 to 24 shape and read the release notes of the JDK you actually compile against.
- Not a pool: a scope is created per unit of work and lives inside one method; long-lived workers still belong in an executor.
- Observable by construction: nested scopes form a tree, and JSON thread dumps show subtasks as children of their scope, which free-form submission can never show.
The guarantees are the point and they have been stable; the spelling has not.
When a scope fits, and the conversion playbook
Reach for a scope when a method fans work out for a single logical unit and cannot answer until that unit is done. Skip it when the tasks outlive the request (that is a pool), when nobody waits for the outcome (fire and forget), or when there is a single task (just call it).
- Name the unit: the method whose result needs every subtask is the owner of the scope.
- Pick the policy from the question being asked: all results required means ShutdownOnFailure, any result is enough means ShutdownOnSuccess, a budget means joinUntil.
- Replace submit() with fork(), and keep each handle as a Supplier (or a Subtask when the state matters).
- Replace the row of get() calls with one join, then the policy call: throwIfFailed() or result().
- Read results after the join, inside the same block; never call get() before it.
- Make every subtask interrupt-friendly: let InterruptedException propagate, check the flag in loops, keep the blocking sections short.
One block, one unit of work: fork, join as a unit, then decide, with no task left outside.
Remember
A scope turns a fan-out into a statement with an entry and an exit, and the guarantees come from that shape.
- Lifetime is lexical: the block cannot exit before every forked thread has finished; join() is the decision point, close() is the final wait.
- Failure is a policy: ShutdownOnFailure cancels the survivors on the first failure and reports it as an ExecutionException cause; ShutdownOnSuccess cancels them on the first success and returns that result.
- Cancellation is interruption: subtasks must cooperate, or the block waits for them, which is a delay rather than a leak.
- Preview, still moving: constructors and subclasses through JDK 24, open() plus a Joiner policy from JDK 25, with --enable-preview either way.
Unstructured submit() leaks work; a scope cannot.
The scope that waited for a subtask that would not leave
A team moved a fan-out to ShutdownOnFailure and expected the block to unwind as soon as the first call failed. join() did return immediately, and then the block sat in close() for the full client timeout: the cancelled subtask was parked in an HTTP call whose library ignored the interrupt. The scope was keeping its promise, which is the point: no thread it started is still running when the block exits. The fix was not to weaken the scope but to make the subtask interruption-responsive, with a client that has a timeout or a read that can be interrupted. Structure guarantees the wait; cooperation decides how long it is.
Interview angles
What does structured concurrency add on top of an ExecutorService?+
A lexical lifetime. Subtasks are forked inside a block, joined as a unit, and the block cannot exit while they run; a fail-fast policy cancels the survivors. With submit() and Future, all of that coordination is manual.
It is not an executor at all: the class deliberately does not implement ExecutorService, because that interface permits free-form submission while the scope enforces structure at run time, including which threads may fork.
Common misconception: It is a faster or safer executor.
Under ShutdownOnFailure, what happens to the other subtasks when one fails?+
The policy captures the first failure and shuts the scope down: unfinished threads are interrupted, new forks do not start, and the owner wakes from join(). throwIfFailed() then throws an ExecutionException with that first failure as its cause.
join() or close(): who waits for what?+
join() stops early when the scope shuts down, which can be before the cancelled threads have finished. close(), through try-with-resources, waits for every thread the scope started. That is why an interruption-ignoring subtask delays the block.
joinUntil(Instant) is the deadline variant: it throws TimeoutException when the deadline passes, then the try-with-resources shuts the scope down and close waits for the cancelled subtasks to stop.
Follow-up: Where does a deadline fit into that picture?
ShutdownOnFailure or ShutdownOnSuccess?+
Failure when every result is required and one failure makes the rest pointless; success when equivalent attempts race and the first answer wins. The policy method differs as well: throwIfFailed() against result().
What does Subtask.state() tell you, and what does it not?+
SUCCESS, FAILED or UNAVAILABLE. UNAVAILABLE is the cancellation bucket, not an error state: forked after shutdown, still running at shutdown, or finished after it. It says nothing about why, and get() outside SUCCESS throws IllegalStateException.
The policies are small subclasses over one hook, handleComplete(Subtask), which is called for subtasks that complete successfully or fail before shutdown, and never for UNAVAILABLE ones.
The API is still preview: what should a team do about that?+
Wrap it behind a small adapter, pin the JDK, and read the release notes on upgrade, because previews since JDK 21 have changed the shape, with JDK 25 moving to open() plus a Joiner policy. If churn is unacceptable, keep the fan-out but isolate it in one place so the eventual migration is small.