StructuredTaskScope Joiners in Java: Collecting Results, Waiting for All and allUntil
A Joiner decides when join() returns and what it gives back. The built-in joiners in Java 27 and 28: awaitAllSuccessfulOrThrow, allSuccessfulOrThrow returning a List, allUntil for collecting every outcome or stopping on your own condition, and custom exception types for join().
kvi5hnuCode Sprout team member8 min readOn this page
The default StructuredTaskScope.open() has one policy built in: wait until all subtasks succeed, and cancel everything on the first failure. Real operations need other policies. A batch of fare lookups wants all the results as a list. A trip dashboard wants whatever it can get, even if one widget fails. A partner search wants to give up after a couple of failures. In StructuredTaskScope, the policy is a separate object, a Joiner, passed to open:
try (var scope = StructuredTaskScope.open(Joiner.<Integer>allSuccessfulOrThrow())) { ... }
What a joiner decides
A joiner answers three questions for its scope:
- When to stop early. After each subtask completes, the joiner may decide to cancel the scope: interrupt the subtasks still running and wake up
join(). - What
join()returns. Nothing, a list of results, a single result, or the subtask handles. - What
join()throws. In Java 27 this is part of the type. A scope isStructuredTaskScope<T, R, R_X>, whereRis whatjoin()returns andR_Xis the exception it throws. The joinerJoiner<T, R, R_X>fixes both.
The Joiner interface has static factories for the common policies:

This article covers all of them except anySuccessfulOrThrow, which gets article 30.
The joiners in action
The program shows each policy with trip-quote examples. It uses the Java 27 preview API (java --enable-preview Joiners.java on Java 27, no flag on Java 28).
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
public class Joiners {
static int fare(String cabin, int ms, int price) throws InterruptedException {
Thread.sleep(ms);
if (price < 0) throw new IllegalStateException(cabin + " fares unavailable");
return price;
}
static String widget(String name, int ms, boolean fails) throws InterruptedException {
Thread.sleep(ms);
if (fails) throw new IllegalStateException(name + " service down");
return name + ": ok";
}
static String partner(int id) throws InterruptedException {
Thread.sleep(100L * id);
if (id == 2 || id == 3) throw new IllegalStateException("partner " + id + " timed out");
return "partner " + id + " has rooms";
}
/** A checked, domain-specific exception for join() to throw (Java 27+). */
static class QuoteException extends Exception {
private static final long serialVersionUID = 1L;
QuoteException(Throwable cause) { super("quote failed: " + cause.getMessage(), cause); }
}
/** Cancels the scope as soon as two subtasks have failed. */
static class CancelAfterTwoFailures implements Predicate<Subtask<?>> {
private final AtomicInteger failures = new AtomicInteger();
@Override public boolean test(Subtask<?> subtask) {
return subtask.state() == Subtask.State.FAILED && failures.incrementAndGet() >= 2;
}
}
public static void main(String[] args) throws Exception {
// 1. allSuccessfulOrThrow: all results as a List, in fork order
try (var scope = StructuredTaskScope.open(Joiner.<Integer>allSuccessfulOrThrow())) {
scope.fork(() -> fare("economy", 300, 212));
scope.fork(() -> fare("premium", 200, 389));
scope.fork(() -> fare("business", 100, 1140));
List<Integer> fares = scope.join();
System.out.println("1. fares in fork order: " + fares);
}
// 2. The same joiner with one failure: the rest are cancelled, join() throws
try (var scope = StructuredTaskScope.open(Joiner.<Integer>allSuccessfulOrThrow())) {
scope.fork(() -> fare("economy", 300, 212));
scope.fork(() -> fare("premium", 100, -1));
scope.join();
} catch (ExecutionException e) {
System.out.println("2. ExecutionException caused by: " + e.getCause().getMessage());
}
// 3. A custom exception type instead of ExecutionException
try (var scope = StructuredTaskScope.open(Joiner.<Integer, QuoteException>allSuccessfulOrThrow(QuoteException::new))) {
scope.fork(() -> fare("first", 100, -1));
scope.join();
} catch (QuoteException e) {
System.out.println("3. " + e.getMessage());
}
// 4. allUntil(s -> false): never cancel, wait for every subtask, inspect each outcome
try (var scope = StructuredTaskScope.open(Joiner.<String>allUntil(s -> false))) {
scope.fork(() -> widget("weather", 100, false));
scope.fork(() -> widget("events", 200, true));
scope.fork(() -> widget("currency", 300, false));
System.out.println("4. trip dashboard:");
for (Subtask<String> s : scope.join()) {
switch (s.state()) {
case SUCCESS -> System.out.println(" " + s.get());
case FAILED -> System.out.println(" (hidden) " + s.exception().getMessage());
case UNAVAILABLE -> System.out.println(" (not finished)");
}
}
}
// 5. allUntil with a predicate: give up after two failures
long start = System.nanoTime();
try (var scope = StructuredTaskScope.open(Joiner.<String>allUntil(new CancelAfterTwoFailures()))) {
for (int id = 1; id <= 6; id++) {
int partnerId = id;
scope.fork(() -> partner(partnerId));
}
List<Subtask<String>> all = scope.join();
long ms = Math.round((System.nanoTime() - start) / 1e6 / 100.0) * 100;
System.out.println("5. stopped after " + ms + " ms, cancelled: " + scope.isCancelled());
for (Subtask<String> s : all) {
System.out.println(" " + s.state() + (s.state() == Subtask.State.SUCCESS ? " " + s.get() : ""));
}
}
}
}
Output:
1. fares in fork order: [212, 389, 1140]
2. ExecutionException caused by: premium fares unavailable
3. quote failed: first fares unavailable
4. trip dashboard:
weather: ok
(hidden) events service down
currency: ok
5. stopped after 300 ms, cancelled: true
SUCCESS partner 1 has rooms
FAILED
FAILED
UNAVAILABLE
UNAVAILABLE
UNAVAILABLE
awaitAllSuccessfulOrThrow: the default
open() with no joiner is the same as open(Joiner.awaitAllSuccessfulOrThrow()). It waits for all subtasks to succeed, cancels on the first failure, and join() returns null. Results come from the individual Subtask handles, which makes it the right choice when the subtasks return different types, like a traveler, a flight and a hotel (article 28).
allSuccessfulOrThrow: a list of results
When all subtasks return the same type, allSuccessfulOrThrow() makes join() return a List<T> of their results. There's no need to keep the handles.
Part 1 of the demo forked the economy fare (300 ms), premium (200 ms) and business (100 ms). They finished in reverse order, but the list came back as [212, 389, 1140]: fork order, not completion order. The list lines up with the inputs, so results.get(i) belongs to the i-th fork.
The failure behaviour is the same as the default (part 2): the first failure cancels the rest and join() throws ExecutionException with that failure as the cause.
A typical use is a batch:
List<Integer> fares(List<String> cabins) throws InterruptedException, ExecutionException {
try (var scope = StructuredTaskScope.open(Joiner.<Integer>allSuccessfulOrThrow())) {
for (String cabin : cabins) scope.fork(() -> lookUpFare(cabin));
return scope.join();
}
}
The explicit type argument in Joiner.<Integer>allSuccessfulOrThrow() is usually needed because Java can't infer T from a static factory call passed straight to open.
Your own exception type
Each throwing joiner has an overload that takes a Function<Throwable, X> and throws X instead of ExecutionException (new in Java 27). Part 3 used QuoteException::new. The function receives the failed subtask's exception and returns the exception for join() to throw. Since R_X is part of the scope's type, the compiler knows join() throws QuoteException, and the catch needs no unwrapping.
A common choice is an unchecked exception so callers don't need throws clauses, for example Joiner.<Integer, CompletionException>allSuccessfulOrThrow(CompletionException::new). Article 31 compares the options.
allUntil: collect every outcome
allUntil(predicate) is the flexible one. After each subtask completes, it calls the predicate with that subtask, and cancels the scope when the predicate returns true. Either way, join() returns a List<Subtask<T>> with every forked subtask, in fork order, and it never throws because of a subtask failure. You inspect each handle's state yourself.
With a predicate that always returns false, it never cancels: the scope waits for every subtask, successes and failures alike. Part 4 used this for a trip dashboard: the events widget failed, but weather and currency still showed. A switch on state() handles each outcome. This is the replacement for Joiner.awaitAll(), which earlier previews had and Java 27 removed.
allUntil with a condition
Part 5 forked six partner hotel searches, finishing at 100 ms intervals. Partners 2 and 3 failed. The CancelAfterTwoFailures predicate counted failures and returned true on the second one, at 300 ms. The scope was cancelled at that point:
- partner 1 had finished:
SUCCESS - partners 2 and 3 had failed:
FAILED - partners 4 to 6 were interrupted:
UNAVAILABLE
The predicate runs in the thread of the subtask that just completed, so several calls can run at the same time. That's why the counter is an AtomicInteger. A plain int field would lose updates. Create a new predicate (and joiner) for every scope: a counter left over from a previous scope would make the next one cancel too early.
Other useful predicates: "stop once three partners have rooms" (enough results), or "stop on any failure of type AuthenticationException" (no point continuing).
Choosing a joiner
| You want | Use |
|---|---|
| Results of different types, all required | open() (awaitAllSuccessfulOrThrow) |
| A list of same-typed results, all required | allSuccessfulOrThrow() |
| The fastest of several equivalent sources | anySuccessfulOrThrow() (article 30) |
| Every outcome, partial results allowed | allUntil(s -> false) |
| Stop on your own condition | allUntil(predicate) |
| Something else (quorum, best of N, ...) | a custom Joiner (article 33) |
What's current
- The factories shown are the Java 27 (JEP 533) API, unchanged in Java 28 (JEP 543), where the API is final.
- Java 25 and 26 differed:
allSuccessfulOrThrow()returned aStream<Subtask<T>>in Java 25 (aList<T>since Java 26), the race joiner was calledanySuccessfulResultOrThrow()in Java 25,awaitAll()existed until Java 26, failures were reported asFailedException, and theFunctionoverloads didn't exist. Article 37 lists every change. - A joiner object is single-use: create a new one for every scope.
Common questions
Why does allSuccessfulOrThrow return results in fork order?
So results can be matched to inputs by position. Completion order depends on timing and would make the output non-deterministic. If you need to know which finished first, use allUntil or a custom joiner.
Can I mix result types with allSuccessfulOrThrow?
Only by making T a common supertype such as Object, which loses type safety. Use the default open() and typed Subtask handles instead.
Does allUntil(s -> false) throw if every subtask fails?
No. join() returns the list of handles, all FAILED. Deciding what that means is up to your code.
What happens if my allUntil predicate throws?
The exception is passed to the subtask thread's uncaught-exception handler before that thread ends, so it never reaches join() and is easy to miss. Keep predicates simple and free of exceptions.
Summary
- A
Joinerdecides when a scope cancels early, whatjoin()returns and what it throws. In Java 27,RandR_Xare part of the scope's type. - The default
open()usesawaitAllSuccessfulOrThrow(): all must succeed, andjoin()returnsnull. allSuccessfulOrThrow()returns aList<T>of results in fork order and fails fast.- Throwing joiners take an optional
Function<Throwable, X>to throw your own exception type. allUntil(predicate)returns everySubtaskhandle and cancels when the predicate returnstrue.allUntil(s -> false)waits for all outcomes without cancelling.- Predicates and joiners run in subtask threads, so they must be thread-safe and must not be reused across scopes.
Practice questions
Five fare lookups are forked with allSuccessfulOrThrow(). They finish in the order 3, 1, 5, 2, 4. What order are the results in, and why is that useful?
Answer
Fork order: 1, 2, 3, 4, 5. Result i always belongs to the i-th fork, so results can be matched with their inputs by index without any extra bookkeeping, whatever the timing.
A developer stores a CancelAfterTwoFailures predicate in a static field and reuses it for every request's scope. What goes wrong?
Answer
The failure counter is shared across scopes and never resets. After two failures in total, across any requests, every later scope is cancelled on its first failure. Concurrent requests also share it. Predicates and joiners must be created per scope.
A dashboard uses open() (the default joiner) to load five widgets. One widget's service is down, and the whole dashboard fails. Which joiner fits better, and how does the code change?
Answer
Joiner.allUntil(s -> false), which waits for every widget without cancelling and returns all the handles. After join(), loop over the handles and render each one according to its state(): the result for SUCCESS, a placeholder for FAILED. The default joiner is all-or-nothing, which is wrong for independent widgets.
Previous: StructuredTaskScope in Java: fork(), join() and the Subtask Handle
Next: Racing Subtasks in Java: anySuccessfulOrThrow and Hedged Requests

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.