Estimate project
← All posts

Java's Structured Concurrency and Scoped Values

Thanks to the work on JEP-505, Java 25 brings structured concurrency. This article, refreshed in September 2025, explains the idea behind structured concurrency, contrasts it with the existing API, and looks at the problems it addresses.

5 min read
Javastructured concurrencyproject loomuncoverjavajava 25

Thanks to the work on JEP-533, Java 25 brings structured concurrency. This article, refreshed in September 2025, explains the idea behind structured concurrency, contrasts it with the existing API, and looks at the problems it addresses.

This article received an update on September 9, 2026.

What is structured concurrency

With structured concurrency, every subtask is tied to the scope of its parent task and cannot outlive it – in the same way that a method call cannot run longer than the method that made it.

This makes concurrent code far easier to reason about: no orphaned background threads keep running once the parent is done, error handling becomes more predictable because failures can be dealt with in a single place, and the whole system is easier to observe and debug.

In practice, it guards against the usual traps of uncontrolled concurrency, such as thread leaks or tasks hanging around forever, which frequently result in brittle, hard-to-maintain systems.

In Java, structured concurrency works with the virtual threads introduced by Project Loom. Since virtual threads are extremely lightweight, spawning new tasks costs next to nothing, which keeps this approach practical and efficient even in heavily concurrent applications.

Example: invoice generation with structured concurrency

To show what’s wrong with the existing API, let’s take a simple example: producing an invoice. We need to retrieve the issuer, the customer and the list of items. Doing that one after another on a single thread works, but slowly. It would be better to fetch the data in parallel.

Let’s start by looking at how this is done with ExecutorService.

(Un)structured concurrency

Invoice generateInvoice() throws ExecutionException, InterruptedException {
    try (final var executor = Executors.newFixedThreadPool(3)) {
        Future<Issuer> issuer = executor.submit(this::findIssuer);
        Future<Customer> customer = executor.submit(this::findCustomer);
        Future<List<Item>> items = executor.submit(this::findItems);

        return new Invoice(issuer.get(), customer.get(), items.get());
    }
}

This approach comes with a few problems:

  • If findCustomer runs longer than findItems, and findItems throws an exception,
    the code will block on customer.get() until the thread running findCustomer completes. We therefore waste resources waiting for that subtask to end.
  • If the thread that calls generateInvoice() gets interrupted, the subtasks in the executor aren’t interrupted and are leaked.
    They may even keep running indefinitely, out of control.

Structured concurrency

Invoice generateInvoice() throws InterruptedException,  ExecutionException {
    try (var scope = StructuredTaskScope.open(
            StructuredTaskScope.Joiner.allSuccessfulOrThrow() // (1)
    )) {
        Subtask<Issuer> issuer = scope.fork(this::findIssuer);
        Subtask<Customer> customer = scope.fork(this::findCustomer);
        Subtask<List<Item>> items = scope.fork(this::findItems);

        scope.join(); // (2)

        return new Invoice(issuer.get(), customer.get(), items.get());
    }
}
  • (1): A new StructuredTaskScope is created through the open() factory method with the allSuccessfulOrThrow() policy.
    Should findIssuer, findCustomer or findItems throw an exception, the remaining subtasks get canceled and the scope fails.
  • (2): Blocks until every subtask in the scope has finished and throws an exception if any of them failed.
    Note that by default scope.join() throws an ExecutionException when one of the subtasks fails. We can, however, configure it to throw any custom exception of our choosing. That requires a small tweak to line (1): calling StructuredTaskScope.Joiner.allSuccessfulOrThrow(MyCustomException::new). We’d then also have to declare MyCustomException in the generateInvoice() throws clause in place of the default ExecutionException.

The code above doesn’t suffer from the problems described before:

  • If findCustomer runs longer than findItems, but findItems throws an exception, the longer-running task gets canceled.
  • If the thread that calls generateInvoice() gets interrupted, the cancellation propagates to the subtasks.
  • Every subtask finishes before the scope is exited.

At first sight little seems different: StructuredTaskScope replaces ExecutorService, and since both implement AutoCloseable, try-with-resources works for each. The difference matters, though: ExecutorService typically relies on platform threads, whereas StructuredTaskScope uses the lightweight virtual threads from the Loom project. In addition, ExecutorService hands back Future<T>, while here we deal with Subtask<T>.

Structured concurrency policies

A policy is a set of rules defining how a StructuredTaskScope reacts when its subtasks succeed or fail.
The new API implements them as Joiners.

allSuccessfulOrThrow

When any subtask fails, the others are canceled and the scope fails. This suits our invoice example well – every piece of data has to be there.

anySuccessfulOrThrow

As soon as one subtask succeeds, the remaining ones are stopped; if all of them fail, an exception is thrown. This comes in handy when querying several sources for the same data where only the quickest one counts – the classic race condition scenario.

allUntil

Keeps all subtasks running until a condition is satisfied, and then cancels the remaining ones.

Other policies

When necessary, you can write your own policy by implementing a custom StructuredTaskScope.Joiner<T, R, R_X extends Throwable>.

Scoped values

Scoped values provide a simple and safe way to share immutable data across methods and child threads. They are easier to reason about than ThreadLocal and cheaper, especially when combined with virtual threads and structured concurrency.

In JDK 25 (JEP 506) the scoped values API is final. There’s one minor difference from the previews: the orElse method doesn’t accept null anymore.

Example: request ID in logging

import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;

import static java.lang.ScopedValue.where;

public class LoggerExample {

    private static final ScopedValue<String> REQUEST_ID =
            ScopedValue.newInstance();

    static void main() throws InterruptedException, ExecutionException {
        try (var scope = StructuredTaskScope
                .open(Joiner.allSuccessfulOrThrow())) {
            scope.fork(() -> where(REQUEST_ID, "abc-123")
                    .run(Main::handleRequest));
            scope.fork(() -> where(REQUEST_ID, "xyz-789")
                    .run(Main::handleRequest));

            scope.join();
        }
    }

    static void handleRequest() {
        log("handleRequest: start");

        try (var scope = StructuredTaskScope
                .open(Joiner.allSuccessfulOrThrow())) {
            scope.fork(Main::queryDatabase);
            scope.fork(Main::callExternalService);
            scope.join();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }

        log("handleRequest: done");
    }

    static void queryDatabase() {
        log("Querying database...");
    }

    static void callExternalService() {
        log("Calling external service...");
    }

    static void log(String message) {
        String rid = REQUEST_ID.isBound() ?
                REQUEST_ID.get() : "<unbound>";
        System.out.println("[" + rid + "] " + message);
    }
}
  1. A scoped value REQUEST_ID is declared to store the request identifier.
  2. Inside main(), two tasks are forked, and each binds REQUEST_ID to its own value (abc-123, xyz-789).
  3. handleRequest opens a structured scope and runs subtasks in parallel; every subtask automatically sees the right bound request ID.
  4. The log method looks up REQUEST_ID dynamically, so each message carries the correct request ID without it being passed as an argument.

Example output:

[xyz-789] handleRequest: start
[abc-123] handleRequest: start
[abc-123] Querying database...
[xyz-789] Querying database...
[xyz-789] Calling external service...
[xyz-789] handleRequest: done
[abc-123] Calling external service...
[abc-123] handleRequest: done

This demonstrates how scoped values allow context to flow cleanly and efficiently along the call chain and down into subtasks.

Summary

Structured concurrency and scoped values are a valuable addition to Java’s standard API, making concurrent code simpler to write.

  • Structured concurrency (JEP 533) allows a group of subtasks to be handled as one unit of work, with predictable cancellation and error handling.
  • Scoped values (JEP 506) offer an efficient, safe way to share immutable context data across methods and threads, free of the issues that come with ThreadLocal.