Nested Scopes in Java: Building Task Trees With StructuredTaskScope
A subtask can open its own StructuredTaskScope, and the scopes form a tree. How failures travel up through nested join() calls, how cancellation and deadlines flow down through interrupts, unwrapping nested ExecutionException causes, and the nesting rules the API enforces.
kvi5hnuCode Sprout team member8 min readOn this page
A subtask is ordinary code running in its own thread, so it can do anything the owner can, including opening a StructuredTaskScope of its own. When it does, it becomes the owner of that inner scope, and the scopes form a tree: the request at the root, its subtasks below, their subtasks below those. Structured concurrency scales to any depth because every level follows the same local rules.
A two-level trip
A multi-leg trip needs flights for every leg and a hotel. The flights are a natural sub-operation: one subtask that fans out, one inner subtask per leg.

The program runs the trip four times: all good, a leg fails, the hotel fails, and the trip's deadline passes. It uses the Java 27 preview API (java --enable-preview Itinerary.java on Java 27, no flag on Java 28).
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class Itinerary {
static final List<String> events = new CopyOnWriteArrayList<>();
static String call(String what, int ms, boolean fails) throws InterruptedException {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
events.add(what + " cancelled");
throw e;
}
if (fails) throw new IllegalStateException(what + " failed");
return what;
}
/** A subtask of the trip scope that is itself the owner of a scope: one leg per subtask. */
static List<String> flights(List<String> legs, String failingLeg, int legMs)
throws InterruptedException, ExecutionException {
try (var legScope = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow(),
cf -> cf.withName("flight-legs"))) {
for (String leg : legs) legScope.fork(() -> call(leg, legMs, leg.equals(failingLeg)));
return legScope.join();
} catch (InterruptedException e) {
events.add("flights interrupted while joining its legs");
throw e;
}
}
static String trip(String failingLeg, boolean hotelFails, int legMs, Duration timeout)
throws InterruptedException, ExecutionException {
try (var tripScope = StructuredTaskScope.open(Joiner.awaitAllSuccessfulOrThrow(),
cf -> cf.withName("trip").withTimeout(timeout))) {
Subtask<List<String>> flights = tripScope.fork(
() -> flights(List.of("LIS-AMS", "AMS-OSL", "OSL-TOS"), failingLeg, legMs));
Subtask<String> hotel = tripScope.fork(() -> call("hotel", 200, hotelFails));
tripScope.join();
return flights.get() + " + " + hotel.get();
}
}
static void run(String label, String failingLeg, boolean hotelFails, int legMs, Duration timeout)
throws InterruptedException {
events.clear();
try {
System.out.println(label + trip(failingLeg, hotelFails, legMs, timeout));
} catch (ExecutionException e) {
Throwable cause = e.getCause();
System.out.println(label + "failed: " + cause.getClass().getSimpleName()
+ (cause.getMessage() != null ? ": " + cause.getMessage() : ""));
}
System.out.println(" events: " + events.stream().sorted().toList());
}
public static void main(String[] args) throws InterruptedException {
run("1. ", null, false, 100, Duration.ofSeconds(5)); // everything succeeds
run("2. ", "AMS-OSL", false, 100, Duration.ofSeconds(5)); // a leg fails deep in the tree
run("3. ", null, true, 1000, Duration.ofSeconds(5)); // the hotel fails: cancel flows down
run("4. ", null, false, 1000, Duration.ofMillis(300)); // the trip deadline bounds the whole tree
}
}
Output:
1. [LIS-AMS, AMS-OSL, OSL-TOS] + hotel
events: []
2. failed: ExecutionException: java.lang.IllegalStateException: AMS-OSL failed
events: [hotel cancelled]
3. failed: IllegalStateException: hotel failed
events: [AMS-OSL cancelled, LIS-AMS cancelled, OSL-TOS cancelled, flights interrupted while joining its legs]
4. failed: CancelledByTimeoutException
events: [AMS-OSL cancelled, LIS-AMS cancelled, OSL-TOS cancelled, flights interrupted while joining its legs]
Failure goes up
In run 2, leg AMS-OSL failed at 100 ms. Step by step:
- In the inner
flight-legsscope,allSuccessfulOrThrowcancelled the other legs (they had already finished at 100 ms, so there was nothing to cancel) and itsjoin()threwExecutionException. - That exception left
flights(), so the flights subtask failed in the trip scope. - The trip scope's joiner cancelled its remaining subtask, the hotel (
hotel cancelled), and itsjoin()threw.
Each scope handled only its own subtasks, and the failure climbed one level at a time, exactly like an exception climbing through nested method calls.
Nested causes
Look at the cause in run 2: ExecutionException: java.lang.IllegalStateException: AMS-OSL failed. The trip's ExecutionException has as its cause the inner scope's ExecutionException, whose cause is the leg's exception. Each level of nesting adds a wrapper. There are two clean ways to deal with it:
- Translate at each level. Have the inner method catch
ExecutionExceptionand throw a meaningful exception, such asFlightsUnavailable(e.getCause()), or open the inner scope with a joiner'sFunctionoverload (article 31). The outer level then sees one domain exception. - Unwrap when handling. Walk the chain to the root cause:
Throwable cause = e.getCause();
while (cause instanceof ExecutionException nested && nested.getCause() != null) {
cause = nested.getCause();
}
Cancellation goes down
In run 3, the hotel failed at 200 ms while the legs (1,000 ms each) were still running:
- The trip scope cancelled itself and interrupted its other subtask, flights.
- The flights subtask was blocked in its inner
join(), which threwInterruptedException(flights interrupted while joining its legs). - Leaving the inner try block ran
close()onflight-legs, which cancelled all three legs and waited for them. - Only then did the flights subtask end, and only then could the trip scope's
close()complete.
Nobody wrote cancellation code for the legs. Interrupting the inner owner was enough, because the inner scope's own rules took over. That's the point of nesting: cancellation from the root reaches every leaf.
Deadlines bound the whole tree
Run 4 gave the trip scope a 300 ms deadline and no deadline at all to the inner scope. At 300 ms the trip scope was cancelled, which interrupted flights, which cancelled the legs, the same chain as run 3. The outer deadline bounded the entire tree, and the trip's join() reported the timeout as CancelledByTimeoutException.
An inner scope can have its own, shorter timeout when one branch has a tighter budget. It can't extend the outer one: the outer cancellation interrupts it whatever its own setting.
The nesting rules
The API checks that scopes really nest:
- Inner scopes close before outer ones. A scope opened while another one is open in the same thread is nested inside it. Closing the outer scope first throws
StructureViolationException(article 27). With try-with-resources this happens automatically. - Each scope has one owner. A subtask can open scopes, but it can't fork into its parent's scope. Only the parent's owner may do that (
WrongThreadException). - Scoped values follow the tree. Subtasks inherit the scoped-value bindings that were in place when their scope was opened. Forking with different bindings from those captured at
open()throwsStructureViolationException(article 41).
Nesting also works without threads: the owner can open a second scope inside the first one's block, for example a follow-up fan-out that depends on the first one's results. It's then nested in the same thread and must be closed first, which try-with-resources ensures.
Designing with nested scopes
- Nest where the domain nests. A sub-operation that is meaningful on its own, such as "find flights for all legs", is a good candidate for its own method and its own scope. The method signature hides the fan-out inside.
- Choose the joiner per level. The legs are all-or-nothing, but a deeper level could race two airline APIs per leg with
anySuccessfulOrThrow. Every level picks the policy that suits it. - Name the scopes.
withName("trip")andwithName("flight-legs")show up in JSON thread dumps, which display the tree of scopes (article 36). - Mind the fan-out. A tree multiplies: 10 legs times 3 airlines times 2 retries is 60 virtual threads per request, which is fine for threads, but not necessarily for the services they call. Limit downstream concurrency with semaphores (article 12).
What's current
- Nesting and its rules are unchanged across the Java 25 to Java 28 versions of the API. Java 28 makes the API final (JEP 543).
- JSON thread dumps from
jcmd <pid> Thread.dump_to_file -format=jsonshow nested scopes as nested containers, each with its owner and threads.
Common questions
Does an inner scope automatically inherit the outer scope's timeout? No. Each scope has its own configuration. But when the outer deadline passes, the outer scope interrupts the inner scope's owner, so the inner scope is cancelled anyway. In practice, the outer deadline bounds the tree.
What happens if the inner method catches InterruptedException and carries on?
The inner scope is still cancelled when its block exits, but the subtask itself keeps working with its interrupt status cleared, so later blocking calls don't stop it, and the outer scope's close() waits for it. Restore the interrupt flag and rethrow, or let the exception propagate.
Can a subtask pass its own scope to its children?
No. Only the owner can fork into a scope, so children would get WrongThreadException. Children that need to fan out open their own scopes.
Is there a limit on nesting depth? No fixed limit. Each level costs a few virtual threads and objects. The practical limits are the call stack and the load on downstream services.
Summary
- A subtask can open its own scope and become its owner. Nested scopes form a tree rooted at the request.
- Failures travel up: an inner
join()throws, the subtask fails, and the outer scope's joiner reacts. Each level adds anExecutionExceptionwrapper unless you translate it. - Cancellation travels down: an outer cancellation interrupts the inner owner, whose
join()throwsInterruptedException, and the innerclose()cancels its subtasks. An outer deadline bounds the whole tree. - The API enforces nesting: inner scopes close first, only owners fork, and scoped-value bindings must match the scope's.
Practice questions
A request owns scope A. Subtask X of A opens scope B with three subtasks. Subtask Y of A fails. Describe what happens to B's subtasks.
Answer
A cancels and interrupts X. X is the owner of B and is probably waiting in B.join(), which throws InterruptedException. Leaving X's try-with-resources block runs B.close(), which cancels (interrupts) B's three subtasks and waits for them. Then X ends, and A's close() can finish.
Logs show ExecutionException: java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: java.net.SocketTimeoutException. What does that tell you, and how can the code improve the error?
Answer
The failure happened three levels deep: a SocketTimeoutException in a subtask of a scope nested inside two others, each of which added an ExecutionException wrapper. Translate at each level into domain exceptions (catch ExecutionException and throw, say, FlightsUnavailable(e.getCause()), or use joiner Function overloads), or unwrap to the root cause before reporting.
The outer scope has a 2-second timeout, and an inner scope has a 5-second timeout. How long can the inner subtasks run?
Answer
At most about 2 seconds from when the outer scope was opened. At the outer deadline the outer scope cancels and interrupts the inner scope's owner, so the inner scope is cancelled no matter what its own timeout says.
Previous: Memory Visibility in Structured Concurrency: What fork() and join() Guarantee
Next: Observing Structured Concurrency: Scope Names, Thread Dumps and Task Trees

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.