Structured concurrency
Structured concurrency treats a group of related tasks running in different threads as one unit of work: they start together, are cancelled together, and are guaranteed to finish before the code that started them continues. In Java it is still a preview API, with the seventh preview in JDK 27 (JEP 533); JDK 28, due in March 2027, makes it final (JEP 543). This page explains the model, runs it on JDK 25, compares it with ExecutorService, and writes a custom joiner.
Contents
What structured concurrency means
Most concurrent Java code is unstructured: a method submits tasks to an ExecutorServiceFuture
Structured concurrency applies the idea of structured programming to threads: if a task splits into concurrent subtasks, they all return to the same place, the task's code block. In Java the block is a StructuredTaskScope
- Fork:
starts each subtask in its own thread, a virtual thread by default.scope.fork(callable) - Join:
waits until a joiner policy decides the outcome: all succeeded, one failed, the first succeeded, or a timeout expired.scope.join() - Cancel: once the outcome is decided, the scope interrupts the subtasks that are still running.
- Close: leaving the block waits until every subtask thread has ended, so no subtask can outlive the code that started it.
The subtasks form a tree under their owner thread. That tree is what gives the other benefits: subtasks inherit the owner's
| API | Since | Lifetime of tasks | On failure | Best for |
|---|---|---|---|---|
ExecutorServiceFuture | Java 5 | Unbounded, until done or cancelled by hand | Siblings keep running | Independent background jobs |
CompletableFuture | Java 8 | Unbounded | Siblings keep running; composition by callbacks | Asynchronous pipelines |
ForkJoinPool | Java 7 | Bounded by join | Exception rethrown at join | Divide-and-conquer CPU work |
StructuredTaskScope | Preview since Java 21 | Bounded by the scope's block | Siblings cancelled automatically | Fan-out of I/O calls within one request |
Status and versions
StructuredTaskScope--enable-preview
| JDK | JEP | What changed |
|---|---|---|
| 19, 20 | JEP 428, 437 | Incubator module jdk.incubator.concurrent |
| 21 to 24 | JEP 453, 462, 480, 499 | Subclass API: new StructuredTaskScope.ShutdownOnFailure()join().throwIfFailed() |
| 25 | JEP 505 (fifth preview) | New API: StructuredTaskScope.open(...)Joiner |
| 26 | JEP 525 (sixth preview) | anySuccessfulResultOrThrowanySuccessfulOrThrowallSuccessfulOrThrowListJoiner.onTimeoutopen(Joiner, ...)UnaryOperator |
| 27 | JEP 533 (seventh preview) | Still a preview API. The JEP adjusts the API again; check its summary before porting code from JDK 25 or 26 |
| 28 (March 2027) | JEP 543 (final) | Standard API with no changes from JDK 27: remove --enable-preview |
To compile and run an example on JDK 25:
javac --release 25 --enable-preview FanOut.java
java --enable-preview FanOut
Running subtasks in parallel
The basic pattern has four steps:
- Open a scope in a try-with-resources block.
- Call
once per subtask. Each subtask starts at once in its own virtual thread and returns afork handle.Subtask - Call
to wait.join() - Read each result with
.get()
When the block ends, close()
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class FanOut {
static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
static String fetchUser() throws InterruptedException {
Thread.sleep(300);
return "user Ana (request " + REQUEST_ID.get() + ")";
}
static int fetchOrderCount() throws InterruptedException {
Thread.sleep(500);
return 7;
}
static long millisSince(long start) {
return (System.nanoTime() - start) / 1000000;
}
public static void main(String[] args) throws InterruptedException {
ScopedValue.where(REQUEST_ID, "r-42").call(() -> {
long start = System.nanoTime();
// open() with no joiner: join() waits for all subtasks, or throws on the first failure
try (var scope = StructuredTaskScope.open()) {
Subtask<String> user = scope.fork(FanOut::fetchUser);
Subtask<Integer> orders = scope.fork(FanOut::fetchOrderCount);
scope.join(); // both run at the same time
System.out.println(user.get() + ", " + orders.get() + " orders");
long ms = millisSince(start);
System.out.println("finished in under 800 ms (300 + 500 if sequential): "
+ (ms < 800));
}
return null;
});
}
}
Output:
user Ana (request r-42), 7 orders
finished in under 800 ms (300 + 500 if sequential): true
- The whole operation finished in under 800 ms, the time the two calls would take one after the other. On a typical run it takes just over 500 ms, the time of the slowest subtask, because both slept at the same time. The program prints a yes/no check rather than the exact time, which varies a little between runs.
readfetchUser in its own thread. Subtasks forked in a scope inherit the scoped value bindings of the thread that opened it, which plainREQUEST_ID threads do not.new Thread without a joiner uses the default policy: wait for all subtasks, and fail as soon as one fails.open()
Failure cancels the siblings
With an ExecutorService
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class FailFast {
static String slowCall() throws InterruptedException {
try {
Thread.sleep(3000);
return "slow result";
} catch (InterruptedException e) {
System.out.println("slow subtask was interrupted (cancelled)");
throw e;
}
}
static String failingCall() throws InterruptedException {
Thread.sleep(200);
throw new IllegalStateException("inventory service down");
}
public static void main(String[] args) throws InterruptedException {
long start = System.nanoTime();
Subtask<String> slow = null;
try (var scope = StructuredTaskScope.open()) {
slow = scope.fork(FailFast::slowCall);
scope.fork(FailFast::failingCall);
scope.join();
} catch (StructuredTaskScope.FailedException e) {
System.out.println("join threw " + e.getClass().getSimpleName() + ", cause: "
+ e.getCause().getMessage());
}
long ms = (System.nanoTime() - start) / 1000000;
System.out.println("slow subtask state: " + slow.state());
System.out.println("returned in under 1000 ms (not 3000): " + (ms < 1000));
}
}
Output:
slow subtask was interrupted (cancelled)
join threw FailedException, cause: inventory service down
slow subtask state: UNAVAILABLE
returned in under 1000 ms (not 3000): true
- At 200 ms the failing subtask throws. The default policy cancels the scope, which interrupts the slow subtask's sleep. Its message prints first because
waits for every subtask thread to finish before theclose() block runs.catch throwsjoin() on JDK 25 and 26, with the original exception as its cause.FailedException- The slow subtask never produced a result, so its state is
; callingUNAVAILABLE on it would throw.get() - The method returned shortly after the 200 ms failure (typically 200 to 300 ms), far below the 3 seconds the slow call would have taken.
The same failure without a scope
For comparison, the program below runs the same pair of calls, a slow one and one that fails after 200 ms, with a virtual-thread ExecutorServiceFuture
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
// The same two calls as FailFast, written with an ExecutorService and Futures
public class UnstructuredLeak {
static final AtomicBoolean SLOW_FINISHED = new AtomicBoolean();
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor();
long start = System.nanoTime();
Future<String> slow = pool.submit(() -> {
Thread.sleep(1000);
SLOW_FINISHED.set(true); // work nobody needs any more
return "slow result";
});
Future<String> failing = pool.submit(() -> {
Thread.sleep(200);
throw new IllegalStateException("inventory service down");
});
try {
System.out.println(slow.get() + failing.get()); // waits for slow first
} catch (ExecutionException e) {
System.out.printf("caller saw the failure after about %d00 ms%n",
(System.nanoTime() - start) / 100000000);
}
System.out.println("slow task finished anyway: " + SLOW_FINISHED.get());
// Even with failing.get() first, the slow task keeps running unless cancelled
SLOW_FINISHED.set(false);
Future<String> slow2 = pool.submit(() -> {
Thread.sleep(1000);
SLOW_FINISHED.set(true);
return "slow result";
});
try {
pool.submit(() -> {
throw new IllegalStateException("fails at once");
}).get();
} catch (ExecutionException e) {
System.out.println("second attempt failed fast, slow task done? " + slow2.isDone());
}
pool.close(); // waits for the orphan to finish
System.out.println("after close, orphan finished: " + SLOW_FINISHED.get());
}
}
Output:
caller saw the failure after about 1000 ms
slow task finished anyway: true
second attempt failed fast, slow task done? false
after close, orphan finished: true
- The caller waited on
first, so it learned about the failure only after about 1000 ms, although the failure happened at 200 ms. A scope reports the first failure as soon as it happens, whatever the fork order.slow.get() - The slow task finished its work anyway: nothing cancelled it. In a server, that is load spent on a request that has already failed.
- In the second attempt the caller saw the failure at once, but the slow task was still running, and it completed only because
waited for it. Withoutpool.close() it would have finished in the background as an orphan. Fixing this by hand needsclose calls in everycancel(true) , which is exactly the bookkeeping a scope does for you.catch
Other policies: first result wins, and timeouts
A Joinerjoin()anySuccessfulResultOrThrow()
import java.time.Duration;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
public class FirstWins {
static String mirror(String name, long millis) throws InterruptedException {
Thread.sleep(millis);
return name;
}
public static void main(String[] args) throws InterruptedException {
// The first subtask to succeed provides the result; the others are cancelled
try (var scope = StructuredTaskScope.open(Joiner.<String>anySuccessfulResultOrThrow())) {
scope.fork(() -> mirror("eu-mirror", 400));
scope.fork(() -> mirror("us-mirror", 150));
scope.fork(() -> mirror("asia-mirror", 900));
System.out.println("fastest: " + scope.join());
}
// A timeout on the whole scope
try (var scope = StructuredTaskScope.open(Joiner.<String>awaitAll(),
cfg -> cfg.withTimeout(Duration.ofMillis(200)))) {
scope.fork(() -> mirror("very-slow", 5000));
scope.join();
} catch (StructuredTaskScope.TimeoutException e) {
System.out.println("join threw TimeoutException after the 200 ms deadline");
}
}
}
Output:
fastest: us-mirror
join threw TimeoutException after the 200 ms deadline
| Joiner | join() | Cancels the rest when |
|---|---|---|
default (open()awaitAllSuccessfulOrThrow() | nullSubtask | Any subtask fails |
allSuccessfulOrThrow() | Stream of the subtasks (a List | Any subtask fails |
anySuccessfulResultOrThrow() | The first successful result | One succeeds |
awaitAll() | null | Never; waits for all, successful or not |
allUntil(predicate) | Stream of all subtasks | The predicate returns true for a completed subtask |
A custom joiner, and ten thousand subtasks
A JoinerBestEffort
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
// Needs JDK 25 with --enable-preview. The Joiner interface changes in JDK 26 and 27
public class CustomJoiner {
// Keeps every successful result, ignores failures, never cancels the scope
static final class BestEffort<T> implements Joiner<T, List<T>> {
private final ConcurrentLinkedQueue<T> results = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedQueue<String> failures = new ConcurrentLinkedQueue<>();
@Override
public boolean onComplete(Subtask<? extends T> subtask) {
switch (subtask.state()) {
case SUCCESS -> results.add(subtask.get());
case FAILED -> failures.add(subtask.exception().getMessage());
case UNAVAILABLE -> { }
}
return false; // false: do not cancel the other subtasks
}
@Override
public List<T> result() {
System.out.println(" failures ignored: " + failures.size() + " " + failures);
return results.stream().sorted().toList();
}
}
static String price(String shop, int millis, boolean fails) throws InterruptedException {
Thread.sleep(millis);
if (fails) {
throw new IllegalStateException(shop + " timed out");
}
return shop + "=" + (millis / 10);
}
public static void main(String[] args) throws InterruptedException {
try (var scope = StructuredTaskScope.open(new BestEffort<String>())) {
scope.fork(() -> price("shopA", 120, false));
scope.fork(() -> price("shopB", 80, true));
scope.fork(() -> price("shopC", 200, false));
scope.fork(() -> price("shopD", 50, true));
System.out.println("prices: " + scope.join());
}
// 10,000 subtasks, each in its own virtual thread, each sleeping 100 ms
long start = System.nanoTime();
try (var scope = StructuredTaskScope.open(Joiner.<Integer>allSuccessfulOrThrow())) {
for (int i = 0; i < 10000; i++) {
int n = i;
scope.fork(() -> {
Thread.sleep(100);
return n;
});
}
long sum = scope.join().mapToLong(Subtask::get).sum();
long ms = (System.nanoTime() - start) / 1000000;
System.out.println("10,000 subtasks, sum " + sum + ", finished in under 2 s: "
+ (ms < 2000));
}
}
}
Output:
failures ignored: 2 [shopD timed out, shopB timed out]
prices: [shopA=12, shopC=20]
10,000 subtasks, sum 49995000, finished in under 2 s: true
runs once per finished subtask, in the thread that ran it, which is why the collections are concurrent queues. ReturningonComplete means "do not cancel the scope". The failures of shopD and shopB arrived in that order, matching their 50 and 80 ms delays.false is called byresult() after all subtasks are done, and its return value becomes the result ofjoin() : the two successful prices.join()- All 10,000 subtasks ran in their own virtual threads and the scope finished in well under 2 seconds, close to the 100 ms each one slept rather than 10,000 × 100 ms. The sum 49,995,000 is 0 + 1 + ... + 9,999. See
virtual threads for why this costs so little. - The
interface has changed between previews (JDK 26 addedJoiner ), so a custom joiner written for JDK 25 may need small changes on later JDKs.onTimeout
The rules that make it structured
A scope enforces its structure at run time. The program breaks three rules on purpose: it reads a result too early, forks from a thread that does not own the scope, and forks after join()
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
// Needs JDK 25 with --enable-preview
public class ScopeRules {
public static void main(String[] args) throws Exception {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> s = scope.fork(() -> "done");
// Reading a result before join()
try {
s.get();
} catch (IllegalStateException e) {
System.out.println("get() before join(): IllegalStateException");
}
// Forking from a thread that does not own the scope
Thread other = Thread.ofPlatform().start(() -> {
try {
scope.fork(() -> "from another thread");
} catch (RuntimeException e) {
System.out.println("fork() from another thread: "
+ e.getClass().getSimpleName());
}
});
other.join();
scope.join();
System.out.println("after join(): " + s.get() + ", state " + s.state());
// Forking after join()
try {
scope.fork(() -> "too late");
} catch (IllegalStateException e) {
System.out.println("fork() after join(): IllegalStateException");
}
}
}
}
Output:
get() before join(): IllegalStateException
fork() from another thread: WrongThreadException
after join(): done, state SUCCESS
fork() after join(): IllegalStateException
beforeget() threwjoin() , even though the subtask had probably already finished. Results are only valid after the owner has joined.IllegalStateException- Only the thread that opened the scope may call
andfork ; the other thread gotjoin . This keeps the task tree well defined.WrongThreadException - After
, the subtask wasjoin() andSUCCESS returned "done", and a furtherget() was rejected.fork - Scopes must be closed in the reverse order in which they were opened, which try-with-resources guarantees. Breaking this throws
.StructureViolationException - Thread dumps (
) show subtasks nested under the scope that owns them, so you can see which request a thread belongs to.jcmd <pid> Thread.dump_to_file -format=json threads.json
When to use a scope
| Situation | Use |
|---|---|
| Several I/O calls for one request, all needed | StructuredTaskScope.open() |
| Ask several replicas, use the fastest answer | Joiner.anySuccessfulResultOrThrow() |
| Collect whatever succeeds, ignore failures | A custom Joiner |
| A deadline for the whole group | cfg -> cfg.withTimeout(...) |
| Fire-and-forget background work | An ExecutorService |
| Recursive CPU-bound splitting | |
| Production code that must compile unchanged on future JDKs |
The model itself (fork, join, cancel together, close waits) has stayed the same since the first preview; only the API around it keeps changing. Code written today for JDK 25 needs small edits for each later preview, as the version table shows.