StructuredTaskScope in Java: fork(), join() and the Subtask Handle
Fork subtasks with Callable and Runnable, wait with join(), and read results through the Subtask handle: its UNAVAILABLE, SUCCESS and FAILED states, get() and exception(), what cancellation leaves behind, what an interrupted owner sees, and a fork() overload trap. A verified trip-quote demo.
kvi5hnuCode Sprout team member7 min readOn this page
Article 27 described the shape of every structured block: open, fork, join, close. This article looks closely at the middle two steps and at the object they revolve around, the Subtask handle, using the default policy from StructuredTaskScope.open().
fork(): two overloads
<U extends T> Subtask<U> fork(Callable<? extends U> task)
<U extends T> Subtask<U> fork(Runnable task)
Both start the task in a new thread (a virtual thread by default) and return immediately with a Subtask handle. The difference is the result:
fork(Callable)is for work that produces a value, such asfindFlight. ACallablemay also throw checked exceptions, so methods that declarethrows InterruptedExceptionorIOExceptionfit directly.fork(Runnable)is for work with no result, such as recording an audit event. ItsSubtask.get()returnsnullon success. ARunnablecan't throw checked exceptions.
T is the scope's subtask type. With var scope = open(), T is Object, and each fork call infers its own U, so one scope can hand back subtasks with different result types: a Subtask<Traveler>, a Subtask<String> and so on.
join(): one call, all outcomes
join() blocks the owner until the scope's policy decides the outcome. For the default policy (all must succeed):
- When every subtask succeeds,
join()returns normally. Its return type isVoid, so the value isnull. Results come from the handles. - When a subtask fails, the scope is cancelled: subtasks still running are interrupted, no new ones start, and
join()throwsExecutionExceptionwhose cause is the failed subtask's exception. - When the owner is interrupted while waiting,
join()throwsInterruptedException. Leaving the block then runsclose(), which cancels the subtasks and waits for them.
The Subtask handle
A Subtask<T> is a handle, not a Future. It has three methods:
| Method | Returns |
|---|---|
state() | UNAVAILABLE, SUCCESS or FAILED; callable at any time |
get() | the result, only if the state is SUCCESS and the owner has joined |
exception() | the exception, only if the state is FAILED and the owner has joined |
There's no cancel, no isDone, and no blocking get with a timeout. Waiting happens in exactly one place, join(), and cancellation belongs to the scope, not to individual subtasks.

UNAVAILABLE covers both "hasn't finished" and "was cancelled". A subtask that was interrupted by cancellation, or that completed after the scope was cancelled, never moves to SUCCESS or FAILED, so after a failure only the failed subtask (and any that finished earlier) has an outcome to read.
A trip quote with four subtasks
The quote needs the traveler profile (200 ms), a flight (100 ms) and a hotel (300 ms), and it records the search for analytics. The program runs it three ways: all succeed, the flight fails, and the owner is interrupted. It uses the Java 27 preview API, so run it with java --enable-preview TripQuotes.java on Java 27, or without the flag on Java 28.
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class TripQuotes {
record Traveler(String name, String tier) {}
record Quote(Traveler traveler, String flight, String hotel, int price) {}
static final List<String> log = new CopyOnWriteArrayList<>();
static Traveler loadTraveler(String id) throws InterruptedException {
Thread.sleep(200);
return new Traveler("Ana", "gold");
}
static String findFlight(String route) throws InterruptedException {
Thread.sleep(100);
if (route.contains("XXX")) throw new IllegalArgumentException("unknown airport XXX");
return route + " 07:40";
}
static String findHotel(String city) throws InterruptedException {
try {
Thread.sleep(300);
return "Hotel Ribeira, " + city;
} catch (InterruptedException e) {
log.add("findHotel was interrupted"); // the scope cancelled it
throw e;
}
}
static void recordSearch(String id) { // no result, no checked exception
log.add("search recorded for " + id);
}
static Quote quote(String id, String route, String city) throws InterruptedException, ExecutionException {
try (var scope = StructuredTaskScope.open()) {
Subtask<Traveler> traveler = scope.fork(() -> loadTraveler(id));
Subtask<String> flight = scope.fork(() -> findFlight(route));
Subtask<String> hotel = scope.fork(() -> findHotel(city));
Subtask<?> audit = scope.fork(() -> recordSearch(id)); // fork(Runnable)
System.out.println(" forked; states: " + List.of(traveler.state(), flight.state(), hotel.state()));
scope.join();
System.out.println(" joined; states: " + List.of(traveler.state(), flight.state(), hotel.state(), audit.state())
+ ", Runnable subtask result: " + audit.get());
int price = traveler.get().tier().equals("gold") ? 380 : 412;
return new Quote(traveler.get(), flight.get(), hotel.get(), price);
}
}
static long elapsed(long start) { return Math.round((System.nanoTime() - start) / 1e6 / 100.0) * 100; }
public static void main(String[] args) throws InterruptedException {
System.out.println("1. all subtasks succeed");
long start = System.nanoTime();
try {
System.out.println(" " + quote("t-17", "LIS-OPO", "Porto") + " after " + elapsed(start) + " ms");
} catch (ExecutionException e) {
System.out.println(" unexpected: " + e.getCause());
}
System.out.println("2. findFlight fails at 100 ms");
log.clear();
start = System.nanoTime();
try {
quote("t-18", "LIS-XXX", "Porto");
} catch (ExecutionException e) {
System.out.println(" failed after " + elapsed(start) + " ms: " + e.getCause());
}
System.out.println(" log: " + log.stream().sorted().toList());
System.out.println("3. the owner is interrupted while joining");
log.clear();
Thread owner = Thread.ofVirtual().start(() -> {
try {
quote("t-19", "LIS-OPO", "Porto");
} catch (InterruptedException e) {
System.out.println(" owner got InterruptedException; log: " + log.stream().sorted().toList());
} catch (ExecutionException e) {
System.out.println(" unexpected: " + e.getCause());
}
});
Thread.sleep(150);
owner.interrupt();
owner.join();
}
}
Output (times rounded to 100 ms, may differ slightly):
1. all subtasks succeed
forked; states: [UNAVAILABLE, UNAVAILABLE, UNAVAILABLE]
joined; states: [SUCCESS, SUCCESS, SUCCESS, SUCCESS], Runnable subtask result: null
Quote[traveler=Traveler[name=Ana, tier=gold], flight=LIS-OPO 07:40, hotel=Hotel Ribeira, Porto, price=380] after 300 ms
2. findFlight fails at 100 ms
forked; states: [UNAVAILABLE, UNAVAILABLE, UNAVAILABLE]
failed after 100 ms: java.lang.IllegalArgumentException: unknown airport XXX
log: [findHotel was interrupted, search recorded for t-18]
3. the owner is interrupted while joining
forked; states: [UNAVAILABLE, UNAVAILABLE, UNAVAILABLE]
owner got InterruptedException; log: [findHotel was interrupted, search recorded for t-19]
What happened
- Success. Right after forking, all three value subtasks were
UNAVAILABLE. Afterjoin()all four wereSUCCESS. TheRunnablesubtask's result wasnull. The quote took 300 ms, the time of the slowest subtask, because they ran concurrently. - Failure.
findFlightthrew at 100 ms. The scope interruptedfindHotel, which logged it, andjoin()threwExecutionExceptionat 100 ms with the originalIllegalArgumentExceptionas the cause. The audit subtask had already finished, so its log line is there. No subtask outlived the call, and the caller didn't wait for the 300 ms hotel search. - Interrupted owner. The owner was interrupted at 150 ms while waiting in
join(). It receivedInterruptedException, andclose()cancelled the subtasks still running: the hotel search shows up as interrupted. Interrupting the request thread now really does stop its work, which article 26 showed doesn't happen with plain executors.
The catch in the hotel search logs and rethrows the InterruptedException. That's the right reaction to cancellation: stop work and let the exception end the task. Swallowing it would make the subtask keep running, and close() would have to wait for it.
Reading results safely
After join() returns normally under the default policy, every subtask is SUCCESS, so calling get() on each is safe. That's why the typical code is simply:
scope.join();
return new Quote(traveler.get(), flight.get(), hotel.get(), price);
When join() throws, don't read the handles at all. The exception's cause already tells you what failed. Handles of cancelled subtasks are UNAVAILABLE, and both get() and exception() throw IllegalStateException on them. Other policies, where join() returns even though some subtasks failed, are where state() and exception() come in (article 29).
A trap: which fork() did I call?
A lambda whose body is an expression fits both overloads. Java prefers the one with a result, Callable:
List<String> seen = new ArrayList<>();
Subtask<?> s = scope.fork(() -> seen.add("LIS")); // fork(Callable<Boolean>), not fork(Runnable)
scope.join();
System.out.println(s.get()); // prints true, not null
That's usually harmless, but it surprises people who expect null. A lambda with a void body, such as () -> recordSearch(id) when recordSearch returns void, can only be a Runnable. To force Runnable, use a block body: () -> { seen.add("LIS"); }.
What's current
- In Java 27 (JEP 533) and Java 28 (final, JEP 543), the default
open()scope has the typeStructuredTaskScope<T, Void, ExecutionException>:join()returnsnulland throwsExecutionExceptionon failure. - In Java 25 and 26, the same failure made
join()throwStructuredTaskScope.FailedException, an unchecked exception. Code migrating to Java 27 must catchExecutionExceptioninstead (article 37). Subtaskhas had the same three methods and states since Java 25. It extendsSupplier<T>, soget()can be passed where aSupplieris expected.
Common questions
Why isn't Subtask a Future?
A Future invites blocking get() calls in arbitrary places and per-task cancellation. Both break the structure: waiting belongs in join() and cancellation belongs to the scope. Subtask offers only what is safe after joining.
Can subtasks of one scope return different types?
Yes. With var scope = open(), T is Object, and each fork call infers its own U, so you get typed handles such as Subtask<Traveler> and Subtask<String> from the same scope.
Does join() return the results?
Not with the default policy: it returns null, and results come from the handles. Other joiners make join() return a value directly, such as a List of results or the first successful result (articles 29 and 30).
What thread runs the subtask?
A new virtual thread per fork, unless the scope was configured with another ThreadFactory. The thread ends when the task ends.
Summary
fork(Callable)starts a subtask with a result,fork(Runnable)one without, both in a new thread, returning aSubtaskhandle at once.- With the default policy,
join()returnsnullwhen all succeed, and on the first failure cancels the rest and throwsExecutionExceptionwith the failure as the cause. Subtaskhasstate()(any time), andget()andexception()(only afterjoin()and only in the matching state).- Cancelled subtasks stay
UNAVAILABLE. Subtasks should rethrowInterruptedExceptionso cancellation actually stops them. - An expression lambda like
() -> list.add(x)selectsfork(Callable).
Practice questions
A scope forks findFlight (100 ms) and findHotel (300 ms). findHotel fails at 300 ms. When does join() throw, and what is findFlight's state?
Answer
At 300 ms, when the failure happens. findFlight had already completed successfully at 100 ms, so its state is SUCCESS. The default policy still makes join() throw ExecutionException, with findHotel's exception as the cause.
A subtask catches InterruptedException from Thread.sleep, logs it, and continues with a 2-second CPU-bound loop. The scope is cancelled. What does the owner experience?
Answer
join() returns or throws as soon as the policy decides the outcome, but leaving the block runs close(), which waits for every subtask thread to finish. The owner is held up for the rest of the 2-second loop. The subtask should rethrow (or restore the interrupt and return) so cancellation stops it.
What does this print, and why?
try (var scope = StructuredTaskScope.open()) {
Subtask<?> s = scope.fork(() -> { counter.incrementAndGet(); });
scope.join();
System.out.println(s.get());
}
Answer
null. The lambda has a block body with no return, so it can only be a Runnable, and a Runnable subtask's get() returns null. Written as the expression () -> counter.incrementAndGet(), it would select fork(Callable) and print the counter value.
Previous: Structured Concurrency in Java: The Principles Behind StructuredTaskScope
Next: StructuredTaskScope Joiners in Java: Collecting Results, Waiting for All and allUntil

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.