00:00

Structured Concurrency in Java 25 (Fifth Preview)

Last updated: · Preview in Java 25

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

Syntax.java
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
Commands
javac --release 25 --enable-preview Dashboard.java && java --enable-preview Dashboard

3. Practical Examples

Example 1: All subtasks must succeed

Dashboard.java
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());
        }
    }
}
Output
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

Joiners.java
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");
        }
    }
}
Output
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

Structured task scope with a joiner open creates a scope with a joiner, fork starts subtasks in virtual threads, the joiner observes each completion and can cancel the scope early, and join returns the joiner result. open(joiner) create scope fork virtual thread per subtask joiner decides on each result join() result or exception
Figure 1: The joiner is the policy; the scope guarantees that no subtask outlives it.
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 a Joiner policy.
  • Failures cancel sibling subtasks; timeouts are part of the configuration.
  • Compile and run with --enable-preview.

Related Tutorials

7. References