Structured Concurrency in Java 21 (Preview)
Structured concurrency treats a group of related tasks running in different threads as a single unit of work. In Java 21 it is a preview API (JEP 453) built around StructuredTaskScope: subtasks are forked inside a scope, and the scope does not end until they have all finished or been cancelled.
This tutorial covers the Java 21 API, the two built-in policies, and how to compile preview code. The API changed in later previews, so check the version you use.
1. Why Is Structured Concurrency Needed?
With an ExecutorService, nothing ties subtasks to the code that started them. If one subtask fails, the others keep running and waste resources; if the caller is interrupted, its subtasks are not cancelled; and thread dumps do not show which task belongs to which request. Structured concurrency gives concurrent code the same clear start and end as a block of sequential code.
2. Syntax and Preview Flags
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Supplier<String> a = scope.fork(() -> callA());
Supplier<String> b = scope.fork(() -> callB());
scope.join(); // wait for all subtasks
scope.throwIfFailed(); // rethrow the first failure
use(a.get(), b.get());
}
javac --release 21 --enable-preview OrderDetails.java && java --enable-preview OrderDetails
3. Practical Examples
Example 1: Two calls as one unit
import java.util.concurrent.ExecutionException;
import java.util.concurrent.StructuredTaskScope;
import java.util.function.Supplier;
// Preview in Java 21 (JEP 453):
// javac --release 21 --enable-preview OrderDetails.java
// java --enable-preview OrderDetails
public class OrderDetails {
record Details(String customer, String shipping) { }
static String fetchCustomer(int orderId) throws InterruptedException {
Thread.sleep(100);
return "Asha (gold member)";
}
static String fetchShipping(int orderId) throws InterruptedException {
Thread.sleep(150);
return "out for delivery";
}
static Details load(int orderId) throws InterruptedException, ExecutionException {
// Both subtasks run at the same time in virtual threads
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Supplier<String> customer = scope.fork(() -> fetchCustomer(orderId));
Supplier<String> shipping = scope.fork(() -> fetchShipping(orderId));
scope.join(); // wait for both
scope.throwIfFailed(); // propagate the first failure, if any
return new Details(customer.get(), shipping.get());
}
}
public static void main(String[] args) throws Exception {
System.out.println(load(1001));
}
}
Details[customer=Asha (gold member), shipping=out for delivery]
Compile and run: javac --release 21 --enable-preview OrderDetails.java && java --enable-preview OrderDetails
Example 2: Failing fast and taking the fastest result
When one subtask fails, ShutdownOnFailure cancels the other immediately instead of waiting two seconds. ShutdownOnSuccess returns the first successful result and cancels the rest.
import java.util.concurrent.ExecutionException;
import java.util.concurrent.StructuredTaskScope;
import java.util.function.Supplier;
// Preview in Java 21 (JEP 453): compile and run with --enable-preview
public class FailFast {
static volatile boolean slowTaskFinished = false;
static String slowCall() throws InterruptedException {
Thread.sleep(2_000);
slowTaskFinished = true;
return "slow result";
}
static String failingCall() {
throw new IllegalStateException("payment service unavailable");
}
public static void main(String[] args) throws Exception {
long start = System.nanoTime();
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
scope.fork(FailFast::slowCall);
scope.fork(FailFast::failingCall);
scope.join().throwIfFailed();
} catch (ExecutionException e) {
System.out.println("Failed: " + e.getCause().getMessage());
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println("Slow task cancelled, not awaited: " + (!slowTaskFinished && ms < 1_500));
// ShutdownOnSuccess: return the first successful result
try (var scope = new StructuredTaskScope.ShutdownOnSuccess<String>()) {
scope.fork(() -> { Thread.sleep(300); return "mirror-eu"; });
scope.fork(() -> { Thread.sleep(50); return "mirror-in"; });
System.out.println("Fastest mirror: " + scope.join().result());
}
}
}
Failed: payment service unavailable Slow task cancelled, not awaited: true Fastest mirror: mirror-in
Compile and run: javac --release 21 --enable-preview FailFast.java && java --enable-preview FailFast
4. Lifecycle of a Scope
5. How the API Evolved
| Version | JEP | Status |
|---|---|---|
| Java 19 / 20 | 428 / 437 | incubator module |
| Java 21 | 453 | preview: ShutdownOnFailure, ShutdownOnSuccess, fork returns Subtask |
| Java 22 / 23 / 24 | 462 / 480 / 499 | further previews |
| Java 25 | 505 | fifth preview, redesigned around StructuredTaskScope.open() and Joiner |
6. Important Points and Best Practices
- Always use the scope in try-with-resources, and call
join()before reading subtask results. - Preview APIs change: Java 21 code using
ShutdownOnFailuredoes not compile on Java 25. - Subtasks run in virtual threads by default, so blocking calls inside them are cheap.
- Do not use preview APIs in production unless your team accepts upgrading the code with each JDK.
7. Summary
- Structured concurrency is a preview API in Java 21 (JEP 453).
StructuredTaskScopegroups subtasks so they start and finish together.ShutdownOnFailurecancels siblings on error;ShutdownOnSuccessreturns the first result.- Compile and run with
--enable-preview; the API changed in later versions.
Related Tutorials
8. References
Frequently Asked Questions (FAQ)
Q1. Is structured concurrency final in Java 21?
No. It is a preview API in Java 21 (JEP 453) and was still in preview in Java 25.
Q2. What does ShutdownOnFailure do?
It shuts down the scope as soon as one subtask fails, cancelling the remaining subtasks, and lets throwIfFailed() rethrow the failure.
Q3. What does ShutdownOnSuccess do?
It shuts down the scope when the first subtask succeeds and returns that result from result(), cancelling the others.
Q4. How do I compile structured concurrency code on Java 21?
Use javac --release 21 --enable-preview and run with java --enable-preview.