Structured Concurrency in Java 25 (Fifth Preview)
Structured concurrency treats related subtasks as one unit: they start in a scope and all finish, or are cancelled, before the scope closes. In Java 25 it is in its fifth preview (JEP 505), with a redesigned API: scopes are created with StructuredTaskScope.open(), and a Joiner decides how results and failures are combined.
This tutorial covers the Java 25 API, the built-in joiners, timeouts and the preview flags.
1. Why Structured Concurrency?
Concurrent code built on executors has no structure: a failed subtask does not stop its siblings, cancelling the parent does not cancel the children, and nothing guarantees that all threads are finished when a method returns. Structured concurrency ties the lifetime of subtasks to a block of code, just as a method call ties the lifetime of its local variables.
2. Syntax and Preview Flags
try (var scope = StructuredTaskScope.open()) { // default: all must succeed
Subtask<String> a = scope.fork(() -> callA());
Subtask<Integer> b = scope.fork(() -> callB());
scope.join(); // throws FailedException on error
use(a.get(), b.get());
}
StructuredTaskScope.open(Joiner.<T>anySuccessfulResultOrThrow()); // first success wins
StructuredTaskScope.open(Joiner.<T>allSuccessfulOrThrow()); // stream of subtasks
StructuredTaskScope.open(joiner, cf -> cf.withTimeout(duration)); // configuration
javac --release 25 --enable-preview Dashboard.java && java --enable-preview Dashboard
3. Practical Examples
Example 1: All subtasks must succeed
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
// Fifth preview in Java 25 (JEP 505):
// javac --release 25 --enable-preview Dashboard.java && java --enable-preview Dashboard
public class Dashboard {
record View(String profile, int unread) { }
static String profile() throws InterruptedException { Thread.sleep(100); return "Meera, Pune"; }
static int unread() throws InterruptedException { Thread.sleep(150); return 4; }
public static void main(String[] args) throws InterruptedException {
// open(): the default policy requires all subtasks to succeed
try (var scope = StructuredTaskScope.open()) {
Subtask<String> p = scope.fork(Dashboard::profile);
Subtask<Integer> u = scope.fork(Dashboard::unread);
scope.join(); // throws FailedException if any subtask failed
System.out.println(new View(p.get(), u.get()));
}
try (var scope = StructuredTaskScope.open()) {
scope.fork(Dashboard::profile);
scope.fork(() -> { throw new IllegalStateException("inbox service down"); });
scope.join();
} catch (StructuredTaskScope.FailedException e) {
System.out.println("Failed: " + e.getCause().getMessage());
}
}
}
View[profile=Meera, Pune, unread=4] Failed: inbox service down
Compile and run: javac --release 25 --enable-preview Dashboard.java && java --enable-preview Dashboard
Example 2: Joiners and timeouts
import java.time.Duration;
import java.util.List;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
// Fifth preview in Java 25 (JEP 505): compile and run with --enable-preview
public class Joiners {
static String mirror(String name, long ms) throws InterruptedException {
Thread.sleep(ms);
return name;
}
public static void main(String[] args) throws InterruptedException {
// First successful result wins; the others are cancelled
try (var scope = StructuredTaskScope.open(Joiner.<String>anySuccessfulResultOrThrow())) {
scope.fork(() -> mirror("mirror-eu", 300));
scope.fork(() -> mirror("mirror-in", 50));
System.out.println("Fastest : " + scope.join());
}
// Collect all results as a stream of successful subtasks
try (var scope = StructuredTaskScope.open(Joiner.<Integer>allSuccessfulOrThrow())) {
for (int page = 1; page <= 3; page++) {
int p = page;
scope.fork(() -> p * 10);
}
List<Integer> counts = scope.join().map(Subtask::get).toList();
System.out.println("All pages: " + counts);
}
// A timeout configured on the scope
try (var scope = StructuredTaskScope.open(Joiner.awaitAll(), cf -> cf.withTimeout(Duration.ofMillis(100)))) {
scope.fork(() -> mirror("slow", 2_000));
scope.join();
} catch (StructuredTaskScope.TimeoutException e) {
System.out.println("Timed out: scope cancelled the slow subtask");
}
}
}
Fastest : mirror-in All pages: [10, 20, 30] Timed out: scope cancelled the slow subtask
Compile and run: javac --release 25 --enable-preview Joiners.java && java --enable-preview Joiners
4. Scopes and Joiners
| Java 21 (JEP 453) | Java 25 (JEP 505) |
|---|---|
new StructuredTaskScope.ShutdownOnFailure() | StructuredTaskScope.open() |
new StructuredTaskScope.ShutdownOnSuccess<T>() | open(Joiner.anySuccessfulResultOrThrow()) |
join().throwIfFailed() | join() throws FailedException |
joinUntil(deadline) | cf.withTimeout(duration) in the configuration |
5. Important Points and Best Practices
- Always use try-with-resources and call
join()before reading results. - Preview APIs change between releases: code written for Java 21 must be updated for Java 25.
- Subtasks inherit scoped value bindings, which is the clean way to pass context.
- Do not rely on preview APIs in production unless you are ready to update the code with each JDK.
6. Summary
- Structured concurrency is in its fifth preview in Java 25 (JEP 505).
- Create scopes with
StructuredTaskScope.open()and choose aJoinerpolicy. - Failures cancel sibling subtasks; timeouts are part of the configuration.
- Compile and run with
--enable-preview.
Related Tutorials
- Structured Concurrency (Java 21 Preview)
- Scoped Values
- Virtual Threads (Java 21)
- CompletableFuture (Java 8)
7. References
Frequently Asked Questions (FAQ)
Q1. Is structured concurrency final in Java 25?
No. It is in its fifth preview in Java 25 (JEP 505) and requires --enable-preview.
Q2. What is a Joiner?
An object that decides how a scope combines subtask results, for example waiting for all to succeed or returning the first success.
Q3. How do I add a timeout to a scope?
Pass a configuration function, for example open(joiner, cf -> cf.withTimeout(Duration.ofSeconds(2))). join() then throws TimeoutException if the time runs out.
Q4. Does Java 21 structured concurrency code work on Java 25?
No. The API was redesigned; classes such as ShutdownOnFailure were replaced by open() and joiners.