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 ExecutorService and gets Future objects back, and nothing ties the lifetime of those tasks to the method. If the method returns early or throws, the tasks keep running. If one task fails, its siblings are not told. A thread dump shows pool threads, but not which request they are working for.

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 opened in try-with-resources:

  • Fork: scope.fork(callable) starts each subtask in its own thread, a virtual thread by default.
  • Join: scope.join() waits until a joiner policy decides the outcome: all succeeded, one failed, the first succeeded, or a timeout expired.
  • 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 scoped values, failures propagate up to one place, and JSON thread dumps show each subtask nested under the scope that created it.

Ways to run related tasks concurrently
APISinceLifetime of tasksOn failureBest for
ExecutorService + FutureJava 5Unbounded, until done or cancelled by handSiblings keep runningIndependent background jobs
CompletableFutureJava 8UnboundedSiblings keep running; composition by callbacksAsynchronous pipelines
ForkJoinPoolJava 7Bounded by join callsException rethrown at joinDivide-and-conquer CPU work
StructuredTaskScopePreview since Java 21Bounded by the scope's blockSiblings cancelled automaticallyFan-out of I/O calls within one request

Status and versions

StructuredTaskScope has been a preview API since Java 21, and its API has changed between releases, so code from older articles often no longer compiles. The programs on this page were compiled and run on JDK 25, the current long-term support release, with --enable-preview. The table lists the changes in later previews that affect this code.

Structured concurrency previews
JDKJEPWhat changed
19, 20JEP 428, 437Incubator module jdk.incubator.concurrent
21 to 24JEP 453, 462, 480, 499Subclass API: new StructuredTaskScope.ShutdownOnFailure(), then join().throwIfFailed()
25JEP 505 (fifth preview)New API: StructuredTaskScope.open(...) with Joiner policies (used on this page)
26JEP 525 (sixth preview)anySuccessfulResultOrThrow renamed to anySuccessfulOrThrow; allSuccessfulOrThrow returns a List of results; Joiner.onTimeout added; open(Joiner, ...) takes a UnaryOperator
27JEP 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 and recompile

To compile and run an example on JDK 25:

Output
javac --release 25 --enable-preview FanOut.java
java --enable-preview FanOut

Running subtasks in parallel

The basic pattern has four steps:

  1. Open a scope in a try-with-resources block.
  2. Call fork once per subtask. Each subtask starts at once in its own virtual thread and returns a Subtask handle.
  3. Call join() to wait.
  4. Read each result with get().

When the block ends, close() makes sure no subtask is still running. The program fetches a user (300 ms) and an order count (500 ms) at the same time, inside a scoped value binding. The two delays are different so that the elapsed time shows whether they ran in parallel.

Java
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:

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.
  • fetchUser read REQUEST_ID in its own thread. Subtasks forked in a scope inherit the scoped value bindings of the thread that opened it, which plain new Thread threads do not.
  • open() without a joiner uses the default policy: wait for all subtasks, and fail as soon as one fails.

Failure cancels the siblings

With an ExecutorService, if one of two tasks fails, the other keeps running unless you cancel it yourself, and a failed request can leave work going on in the background. A scope cancels the remaining subtasks by interrupting their threads as soon as the policy decides the outcome. Below, one subtask fails after 200 ms while the other would take 3 seconds.

Java
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:

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
  1. 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 close() waits for every subtask thread to finish before the catch block runs.
  2. join() throws FailedException on JDK 25 and 26, with the original exception as its cause.
  3. The slow subtask never produced a result, so its state is UNAVAILABLE; calling get() on it would throw.
  4. 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 ExecutorService and two Futures, then tries again with the failing call checked first.

Java
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:

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 slow.get() 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.
  • 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 pool.close() waited for it. Without close it would have finished in the background as an orphan. Fixing this by hand needs cancel(true) calls in every catch, which is exactly the bookkeeping a scope does for you.

Other policies: first result wins, and timeouts

A Joiner decides when join() returns and what it returns. anySuccessfulResultOrThrow() returns the first successful result and cancels the rest, which suits asking several mirrors and taking the fastest one. The mirrors below answer after 400, 150 and 900 ms, so the US mirror should win. The second part sets a 200 ms timeout on a scope whose only subtask takes 5 seconds.

Java
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:

Output
fastest: us-mirror
join threw TimeoutException after the 200 ms deadline
Built-in joiners on JDK 25
Joinerjoin() returnsCancels the rest when
default (open()), same as awaitAllSuccessfulOrThrow()null; read each SubtaskAny subtask fails
allSuccessfulOrThrow()Stream of the subtasks (a List from JDK 26)Any subtask fails
anySuccessfulResultOrThrow()The first successful resultOne succeeds
awaitAll()nullNever; waits for all, successful or not
allUntil(predicate)Stream of all subtasksThe predicate returns true for a completed subtask

A custom joiner, and ten thousand subtasks

A Joiner is an interface, so a policy that none of the built-in ones provides can be written in a few lines. BestEffort keeps every successful result, records failures without cancelling anything, and returns the sorted results. Two of the four shops fail, at 50 and 80 ms, to show that failures do not stop the others. The second part forks 10,000 subtasks that each sleep 100 ms.

Java
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:

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
  • onComplete runs once per finished subtask, in the thread that ran it, which is why the collections are concurrent queues. Returning false means "do not cancel the scope". The failures of shopD and shopB arrived in that order, matching their 50 and 80 ms delays.
  • result() is called by join() after all subtasks are done, and its return value becomes the result of join(): the two successful prices.
  • 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 Joiner interface has changed between previews (JDK 26 added onTimeout), so a custom joiner written for JDK 25 may need small changes on later JDKs.

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().

Java
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:

Output
get() before join(): IllegalStateException
fork() from another thread: WrongThreadException
after join(): done, state SUCCESS
fork() after join(): IllegalStateException
  • get() before join() threw IllegalStateException, even though the subtask had probably already finished. Results are only valid after the owner has joined.
  • Only the thread that opened the scope may call fork and join; the other thread got WrongThreadException. This keeps the task tree well defined.
  • After join(), the subtask was SUCCESS and get() returned "done", and a further fork was rejected.
  • Scopes must be closed in the reverse order in which they were opened, which try-with-resources guarantees. Breaking this throws StructureViolationException.
  • Thread dumps (jcmd <pid> Thread.dump_to_file -format=json threads.json) show subtasks nested under the scope that owns them, so you can see which request a thread belongs to.

When to use a scope

Choosing a concurrency tool
SituationUse
Several I/O calls for one request, all neededStructuredTaskScope.open() (default joiner)
Ask several replicas, use the fastest answerJoiner.anySuccessfulResultOrThrow() (renamed in JDK 26)
Collect whatever succeeds, ignore failuresA custom Joiner
A deadline for the whole groupcfg -> cfg.withTimeout(...)
Fire-and-forget background workAn ExecutorService; it is not meant to be joined
Recursive CPU-bound splittingForkJoinPool or parallel streams
Production code that must compile unchanged on future JDKsCompletableFuture or an executor until the API is final

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.