00:00

Structured Concurrency in Java 21 (Preview)

Last updated: · Preview in Java 21

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

Syntax.java
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());
}
Commands
javac --release 21 --enable-preview OrderDetails.java && java --enable-preview OrderDetails

3. Practical Examples

Example 1: Two calls as one unit

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

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

Structured task scope lifecycle The scope is opened, subtasks are forked into virtual threads, join waits for them, the policy decides success or failure, and closing the scope guarantees no subtask is still running. open scope try-with-resources fork subtasks virtual threads join policy decides close no leftover threads
Figure 1: Subtasks can never outlive the block that created them.

5. How the API Evolved

VersionJEPStatus
Java 19 / 20428 / 437incubator module
Java 21453preview: ShutdownOnFailure, ShutdownOnSuccess, fork returns Subtask
Java 22 / 23 / 24462 / 480 / 499further previews
Java 25505fifth 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 ShutdownOnFailure does 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).
  • StructuredTaskScope groups subtasks so they start and finish together.
  • ShutdownOnFailure cancels siblings on error; ShutdownOnSuccess returns the first result.
  • Compile and run with --enable-preview; the API changed in later versions.

Related Tutorials

8. References