Structured concurrency
suggest changeWhen a method splits its work into concurrent subtasks, for example loading a user and their orders from two services at once, an ExecutorService gives you no help with the hard parts. If one subtask fails, the others keep running. If the caller is interrupted, the subtasks don't notice. If you forget to wait for a future, its task outlives the method that started it.
Structured concurrency applies the rule of structured programming to threads: subtasks start inside a block of code and are guaranteed to have finished when the block ends. In Java the block is a StructuredTaskScope used in try-with-resources:
- you
forksubtasks inside the scope, each on its own virtual thread join()waits for them, according to a policy called a joiner (all must succeed, first success wins, and so on)- when the policy decides the outcome (a failure, a success, a timeout), the scope cancels the subtasks that are still running
close()never returns while a subtask is still running, so nothing leaks
StructuredTaskScope is a preview API in JDK 25 (JEP 505, the fifth preview) and is still a preview in JDK 26. Preview APIs can change, and this one has changed a lot between releases (see "API changes between releases" at the end). The code in this article targets JDK 25. Output is from JDK 25.0.4.
Related articles: Virtual threads explains the threads that subtasks run on. Cancellation and timeouts covers interruption, which is how a scope cancels subtasks. Callable and Future and CompletableFuture are the unstructured alternatives.
Compiling and running preview code
Preview APIs are disabled unless you opt in, both when compiling and when running:
$ javac -d out UserPage.java
UserPage.java:1: error: StructuredTaskScope is a preview API and is disabled by default.
import java.util.concurrent.StructuredTaskScope;
^
(use --enable-preview to enable preview APIs)
$ javac --enable-preview --release 25 -d out UserPage.java
Note: UserPage.java uses preview features of Java SE 25.
Note: Recompile with -Xlint:preview for details.
$ java -cp out UserPage
Error: LinkageError occurred while loading main class UserPage
java.lang.UnsupportedClassVersionError: Preview features are not enabled for UserPage (class file version 69.65535). Try running with '--enable-preview'
$ java --enable-preview -cp out UserPage
Class files that use preview features are marked with minor version 65535 and only run on the exact JDK release they were compiled for. A class compiled with JDK 25 won't load on JDK 26, even with --enable-preview.
To run a single source file directly, which is what the examples below do:
$ java --enable-preview --source 25 UserPage.java
In Maven, add --enable-preview to maven-compiler-plugin's compilerArgs and to the Surefire argLine. In Gradle, add it to options.compilerArgs of JavaCompile and to jvmArgs of Test and JavaExec tasks.
A first scope
Here a page needs a user and their last order. The two lookups are independent, so we run them at the same time:
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class UserPage {
record User(long id, String name) {}
record Order(long id, String item) {}
record Page(User user, Order order) {}
static User findUser(long id) throws InterruptedException {
Thread.sleep(300); // pretend to call a service
return new User(id, "alice");
}
static Order findLastOrder(long userId) throws InterruptedException {
Thread.sleep(200);
return new Order(9001, "keyboard");
}
static Page loadPage(long id) throws InterruptedException {
try (var scope = StructuredTaskScope.open()) {
Subtask<User> user = scope.fork(() -> findUser(id));
Subtask<Order> order = scope.fork(() -> findLastOrder(id));
scope.join(); // wait for both subtasks
return new Page(user.get(), order.get());
}
}
public static void main(String[] args) throws InterruptedException {
long start = System.nanoTime();
Page page = loadPage(42);
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println(page);
System.out.println("took ~" + (ms / 100 * 100) + " ms");
}
}
Page[user=User[id=42, name=alice], order=Order[id=9001, item=keyboard]]
took ~300 ms
It takes as long as the slowest lookup (300 ms), not the sum of both (500 ms).
The pattern is always the same:
StructuredTaskScope.open()creates a scope. The thread that opens it is its owner.fork(Callable)starts a subtask in a new virtual thread and returns aSubtask<T>handle. There is alsofork(Runnable)for subtasks without a result.join()blocks until the joiner's policy is satisfied. The no-argumentopen()uses "all subtasks must succeed":join()returns once every subtask has succeeded, or throws as soon as one fails.- After
join(),Subtask.get()returns the result. close(), called by try-with-resources, cancels anything still running and waits for it.
Failure cancels the siblings
What makes a scope more than a convenient executor is what happens on failure. In this example one subtask fails after 100 ms while the other would take 5 seconds:
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class Failure {
static long start;
static void log(String msg) {
System.out.printf("%4d ms %s%n", (System.nanoTime() - start) / 1_000_000, msg);
}
static String slow() throws InterruptedException {
try {
Thread.sleep(5_000);
return "slow result";
} catch (InterruptedException e) {
log("slow: interrupted, giving up");
throw e;
}
}
static String broken() throws InterruptedException {
Thread.sleep(100);
throw new IllegalStateException("service unavailable");
}
public static void main(String[] args) throws InterruptedException {
start = System.nanoTime();
try (var scope = StructuredTaskScope.open()) {
Subtask<String> a = scope.fork(Failure::slow);
Subtask<String> b = scope.fork(Failure::broken);
scope.join();
log("never printed");
} catch (StructuredTaskScope.FailedException e) {
log("join failed: " + e.getCause());
}
}
}
119 ms slow: interrupted, giving up
132 ms join failed: java.lang.IllegalStateException: service unavailable
When broken() throws, the scope is cancelled: no new subtasks may start, and every running subtask's thread is interrupted. join() then throws StructuredTaskScope.FailedException, an unchecked exception whose cause is the exception of the first subtask to fail. The whole operation fails in about 100 ms instead of 5 seconds.
Compare the same code with an ExecutorService and futures:
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<String> a = executor.submit(Unstructured::slow); // sleeps 1 s
Future<String> b = executor.submit(Unstructured::broken); // fails after 100 ms
try {
String result = a.get() + b.get(); // waits for slow() first
} catch (ExecutionException e) {
log("failed: " + e.getCause());
}
}
1011 ms slow: finished, but nobody wants the result
1024 ms failed: java.lang.IllegalStateException: service unavailable
a.get() blocks for a full second before we learn that b failed long ago, and slow() runs to completion although its result is thrown away. You can fix this with CompletableFuture.anyOf, callbacks and manual cancel(true) calls, but the scope does it for you.
Cancellation is cooperative, as everywhere in Java: the scope interrupts the subtask's thread, and the subtask has to react, which blocking calls such as Thread.sleep, BlockingQueue.take, socket I/O on virtual threads and HttpClient.send do by throwing InterruptedException. A CPU-bound loop must check Thread.currentThread().isInterrupted(). close() waits for cancelled subtasks to actually finish, so a subtask that ignores interruption delays the end of the scope. See Cancellation and timeouts.
Joiners
The policy that decides when join() returns, and what it returns, is a StructuredTaskScope.Joiner<T, R>. You pass one to open(joiner). T is the result type of the subtasks and R is the type join() returns. The built-in joiners are static factory methods on Joiner:
| Joiner | join() returns |
Cancels the scope when |
|---|---|---|
awaitAllSuccessfulOrThrow() (what open() uses) |
null (Void); read results from the Subtask handles |
a subtask fails |
allSuccessfulOrThrow() |
Stream<Subtask<T>> of all subtasks, in fork order |
a subtask fails |
anySuccessfulResultOrThrow() |
the result T of the first subtask to succeed |
a subtask succeeds |
awaitAll() |
null; inspect each Subtask |
never |
allUntil(predicate) |
Stream<Subtask<T>> of all subtasks |
the predicate returns true for a completed subtask |
The joiners that "throw" do so with FailedException from join().
allSuccessfulOrThrow: fan out over a list
When you fork one subtask per element and want all the results, allSuccessfulOrThrow() saves you from keeping a list of Subtask handles:
import java.util.List;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class FanOut {
static int wordCount(String url) throws InterruptedException {
Thread.sleep(100 + url.length() * 10);
return url.length() * 7;
}
public static void main(String[] args) throws InterruptedException {
List<String> urls = List.of("a.example", "bb.example", "ccc.example");
try (var scope = StructuredTaskScope.open(Joiner.<Integer>allSuccessfulOrThrow())) {
for (String url : urls) {
scope.fork(() -> wordCount(url));
}
List<Integer> counts = scope.join() // Stream<Subtask<Integer>>
.map(Subtask::get)
.toList();
System.out.println(counts);
}
}
}
[63, 70, 77]
The type witness Joiner.<Integer> is needed because Java can't infer the subtask type from open(...) alone. The stream is in fork order, not completion order.
A scope creates a virtual thread per subtask and has no concurrency limit. If you fork 10,000 subtasks that call the same service, guard the call with a Semaphore as described in Virtual threads.
anySuccessfulResultOrThrow: first success wins
To query several replicas and take whichever answers first, use anySuccessfulResultOrThrow(). Failures are ignored as long as one subtask succeeds, and the first success cancels the rest:
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
public class Race {
static String fetch(String mirror, int delayMs, boolean fail) throws InterruptedException {
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
System.out.println(mirror + ": cancelled");
throw e;
}
if (fail) throw new RuntimeException(mirror + " is down");
return "data from " + mirror;
}
public static void main(String[] args) throws InterruptedException {
String result;
try (var scope = StructuredTaskScope.open(Joiner.<String>anySuccessfulResultOrThrow())) {
scope.fork(() -> fetch("eu", 300, false));
scope.fork(() -> fetch("us", 100, true)); // fastest, but fails
scope.fork(() -> fetch("asia", 200, false));
result = scope.join();
} // close() waits until "eu" has finished
System.out.println(result);
try (var scope = StructuredTaskScope.open(Joiner.<String>anySuccessfulResultOrThrow())) {
scope.fork(() -> fetch("eu", 100, true));
scope.fork(() -> fetch("us", 200, true));
scope.join();
} catch (StructuredTaskScope.FailedException e) {
System.out.println("all failed: " + e.getCause().getMessage());
}
}
}
eu: cancelled
data from asia
all failed: eu is down
us fails first and is ignored, asia succeeds at 200 ms, and eu is interrupted. If every subtask fails, join() throws FailedException with the exception of one of them.
awaitAll: keep partial results
Sometimes a failed subtask is acceptable: a price comparison page can show the shops that answered. awaitAll() waits for every subtask and never cancels the scope, so you check each Subtask's state():
import java.util.List;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class Partial {
static String price(String shop) throws InterruptedException {
Thread.sleep(100);
if (shop.equals("shop-b")) throw new IllegalStateException("timeout talking to " + shop);
return shop + ": " + (shop.length() * 3) + ".99";
}
public static void main(String[] args) throws InterruptedException {
List<String> shops = List.of("shop-a", "shop-b", "shop-c");
try (var scope = StructuredTaskScope.open(Joiner.<String>awaitAll())) {
List<Subtask<String>> tasks = shops.stream()
.map(shop -> scope.fork(() -> price(shop)))
.toList();
scope.join(); // never throws because of a failed subtask
for (Subtask<String> t : tasks) {
switch (t.state()) {
case SUCCESS -> System.out.println("ok " + t.get());
case FAILED -> System.out.println("failed " + t.exception().getMessage());
case UNAVAILABLE -> System.out.println("not completed");
}
}
}
}
}
ok shop-a: 18.99
failed timeout talking to shop-b
ok shop-c: 18.99
A Subtask is in one of three states:
SUCCESS:get()returns the result.FAILED:exception()returns what the subtask threw.UNAVAILABLE: the subtask hasn't completed, was cancelled before it completed, or was forked after the scope was cancelled. Bothget()andexception()throwIllegalStateException.
allUntil: stop on a condition
allUntil(predicate) calls the predicate as each subtask completes. When it returns true, the scope is cancelled. join() returns all subtasks, so you can see which ones finished:
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class Until {
static int probe(int n) throws InterruptedException {
Thread.sleep(n * 100L);
return n;
}
public static void main(String[] args) throws InterruptedException {
// stop as soon as some subtask returns a value greater than 2
Joiner<Integer, java.util.stream.Stream<Subtask<Integer>>> joiner =
Joiner.allUntil(t -> t.state() == Subtask.State.SUCCESS && t.get() > 2);
try (var scope = StructuredTaskScope.open(joiner)) {
for (int n = 1; n <= 6; n++) {
int i = n;
scope.fork(() -> probe(i));
}
scope.join().forEach(t -> System.out.println(t.state()
+ (t.state() == Subtask.State.SUCCESS ? " " + t.get() : "")));
System.out.println("cancelled: " + scope.isCancelled());
}
}
}
SUCCESS 1
SUCCESS 2
SUCCESS 3
UNAVAILABLE
UNAVAILABLE
UNAVAILABLE
cancelled: true
allUntil never throws because of a failed subtask. Failures show up as FAILED in the stream.
Writing a custom joiner
When no built-in policy fits, implement Joiner<T, R> yourself. It has three methods:
onFork(subtask): called in the owner thread when a subtask is forked. Rarely needed.onComplete(subtask): called in the subtask's thread when it completes. Returntrueto cancel the scope.result(): called byjoin()in the owner thread once all subtasks are done or the scope is cancelled. Its return value is whatjoin()returns. If it throws,join()throwsFailedExceptionwith that exception as the cause.
onComplete runs concurrently in many subtask threads, so its state must be thread-safe. This joiner implements a write quorum: it succeeds once needed replicas have acknowledged and cancels the others:
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class Quorum {
// Succeeds once `needed` subtasks have succeeded; cancels the rest.
static final class QuorumJoiner<T> implements Joiner<T, List<T>> {
private final int needed;
private final Queue<T> results = new ConcurrentLinkedQueue<>();
private final AtomicInteger successes = new AtomicInteger();
private final AtomicInteger failures = new AtomicInteger();
QuorumJoiner(int needed) { this.needed = needed; }
@Override
public boolean onComplete(Subtask<? extends T> subtask) {
// called by the subtask's thread, so it must be thread-safe
switch (subtask.state()) {
case SUCCESS -> {
results.add(subtask.get());
return successes.incrementAndGet() >= needed; // true = cancel scope
}
case FAILED -> failures.incrementAndGet();
case UNAVAILABLE -> throw new AssertionError();
}
return false;
}
@Override
public List<T> result() {
// called by join() in the owner thread, after all subtasks are done or cancelled
if (successes.get() < needed) {
throw new IllegalStateException("quorum not reached: "
+ successes.get() + " ok, " + failures.get() + " failed");
}
return List.copyOf(results).subList(0, needed);
}
}
static String write(String replica, int ms, boolean fail) throws InterruptedException {
Thread.sleep(ms);
if (fail) throw new RuntimeException(replica + " rejected the write");
return replica;
}
public static void main(String[] args) throws InterruptedException {
try (var scope = StructuredTaskScope.open(new QuorumJoiner<String>(2))) {
scope.fork(() -> write("r1", 300, false));
scope.fork(() -> write("r2", 100, true));
scope.fork(() -> write("r3", 150, false));
scope.fork(() -> write("r4", 200, false));
scope.fork(() -> write("r5", 5_000, false));
System.out.println("acked by " + scope.join());
}
try (var scope = StructuredTaskScope.open(new QuorumJoiner<String>(2))) {
scope.fork(() -> write("r1", 100, true));
scope.fork(() -> write("r2", 150, false));
scope.fork(() -> write("r3", 200, true));
scope.join();
} catch (StructuredTaskScope.FailedException e) {
System.out.println(e.getCause());
}
}
}
acked by [r3, r4]
java.lang.IllegalStateException: quorum not reached: 1 ok, 2 failed
A joiner object belongs to one scope. Create a new one for every open.
Timeouts, names and thread factories
The two-argument open(joiner, configFunction) takes a function that modifies the scope's Configuration. It has three settings:
withTimeout(Duration): when the timeout expires, the scope is cancelled andjoin()throwsStructuredTaskScope.TimeoutException(unchecked, notjava.util.concurrent.TimeoutException).withName(String): a name shown in thread dumps.withThreadFactory(ThreadFactory): creates the subtask threads. The default creates unnamed virtual threads.
A timeout covers the whole scope, which is usually what you want for a request with a deadline:
import java.time.Duration;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class Timeout {
static String call(String name, long ms) throws InterruptedException {
try {
Thread.sleep(ms);
return name + " done";
} catch (InterruptedException e) {
System.out.println(name + ": interrupted after timeout");
throw e;
}
}
static String quote(long slowMs) throws InterruptedException {
try (var scope = StructuredTaskScope.open(
Joiner.<String>awaitAllSuccessfulOrThrow(),
cf -> cf.withTimeout(Duration.ofMillis(500))
.withName("quote"))) {
Subtask<String> rates = scope.fork(() -> call("rates", 100));
Subtask<String> stock = scope.fork(() -> call("stock", slowMs));
scope.join();
return rates.get() + ", " + stock.get();
} catch (StructuredTaskScope.TimeoutException e) {
return "fallback quote (timed out)";
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println(quote(200));
System.out.println(quote(2_000));
}
}
rates done, stock done
stock: interrupted after timeout
fallback quote (timed out)
The catch block runs after try-with-resources has closed the scope, so by the time we return the fallback, the stock subtask has stopped.
A custom thread factory gives subtask threads names, which helps in logs:
ThreadFactory factory = Thread.ofVirtual().name("fetcher-", 0).factory();
try (var scope = StructuredTaskScope.open(
Joiner.<String>allSuccessfulOrThrow(),
cf -> cf.withThreadFactory(factory))) {
for (int i = 0; i < 3; i++) {
scope.fork(() -> Thread.currentThread().getName());
}
scope.join().forEach(t -> System.out.println(t.get()));
}
fetcher-0
fetcher-1
fetcher-2
Nested scopes and how cancellation propagates
A subtask can open its own scope, which gives you a tree of tasks. Cancellation flows down the tree: cancelling a scope interrupts its subtasks, and a subtask that is blocked in its own join() gets InterruptedException, after which its close() cancels and waits for its subtasks. Failures flow up: an exception thrown by an inner scope fails the subtask that owns it.
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class Nested {
static String leaf(String name, long ms) throws InterruptedException {
try {
Thread.sleep(ms);
return name;
} catch (InterruptedException e) {
System.out.println(" " + name + ": cancelled");
throw e;
}
}
// a subtask that itself splits its work into two subtasks
static String profile() throws InterruptedException {
try (var inner = StructuredTaskScope.open()) {
Subtask<String> avatar = inner.fork(() -> leaf("avatar", 2_000));
Subtask<String> bio = inner.fork(() -> leaf("bio", 2_000));
inner.join();
return avatar.get() + "+" + bio.get();
} finally {
System.out.println(" inner scope closed");
}
}
static String recommendations() throws InterruptedException {
Thread.sleep(200);
throw new IllegalStateException("recommendation service down");
}
public static void main(String[] args) throws InterruptedException {
try (var outer = StructuredTaskScope.open()) {
outer.fork(Nested::profile);
outer.fork(Nested::recommendations);
outer.join();
} catch (StructuredTaskScope.FailedException e) {
System.out.println("outer failed: " + e.getCause().getMessage());
}
}
}
avatar: cancelled
bio: cancelled
inner scope closed
outer failed: recommendation service down
(The first two lines can appear in either order.) The failure of recommendations cancels the outer scope, which interrupts profile, which cancels avatar and bio. Only after all four threads have finished does the outer join() throw. The same happens when the owner of the outer scope is interrupted: join() throws InterruptedException and the whole tree is cancelled.
Scoped values are inherited
Subtasks see the scoped values bound in the owner thread when the scope was opened. Scoped values are final in JDK 25, and they are the intended replacement for ThreadLocal for passing context, such as a request id, down a task tree:
static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
static String handle() throws InterruptedException {
try (var scope = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow())) {
scope.fork(() -> "user lookup for " + REQUEST_ID.get());
scope.fork(() -> "order lookup for " + REQUEST_ID.get());
return String.join("\n", scope.join().map(t -> t.get()).toList());
}
}
public static void main(String[] args) throws Exception {
String out = ScopedValue.where(REQUEST_ID, "req-7").call(Inherit::handle);
System.out.println(out);
}
user lookup for req-7
order lookup for req-7
ThreadLocal values are not inherited by subtasks, except InheritableThreadLocal, which is copied into each new thread.
Rules the scope enforces
The structure is checked at run time:
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class Rules {
static void attempt(String what, Runnable r) {
try {
r.run();
System.out.println(what + ": ok");
} catch (RuntimeException e) {
System.out.println(what + ": " + e.getClass().getSimpleName());
}
}
public static void main(String[] args) throws Exception {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> s = scope.fork(() -> "hi");
// 1. results are only available after join()
attempt("get() before join()", s::get);
// 2. only the owner thread may fork or join
Thread t = Thread.ofPlatform().start(() ->
attempt("fork() from another thread", () -> scope.fork(() -> "x")));
t.join();
scope.join();
attempt("get() after join()", () -> System.out.println(" value: " + s.get()));
// 3. fork() is not allowed after join()
attempt("fork() after join()", () -> scope.fork(() -> "late"));
}
// 4. scopes must be closed in the reverse order they were opened
var a = StructuredTaskScope.open();
var b = StructuredTaskScope.open();
attempt("close outer scope first", a::close);
b.close();
}
}
get() before join(): IllegalStateException
fork() from another thread: WrongThreadException
value: hi
get() after join(): ok
fork() after join(): IllegalStateException
close outer scope first: StructureViolationException
Forgetting to call join() is also an error. close() cancels the subtasks, waits for them, and then throws:
try (var scope = StructuredTaskScope.open()) {
scope.fork(() -> { Thread.sleep(1000); return 1; });
} // java.lang.IllegalStateException: Owner did not join after forking
In practice, always use try-with-resources and keep fork and join in the same block. Rule 2 also applies to subtasks: a subtask can't fork into its parent's scope. To split its work further, it opens a nested scope of its own.
Thread dumps show the task tree
Each scope is a thread container, and JSON thread dumps record which container each thread belongs to and which thread owns each container. Run the nested example with named scopes (cf -> cf.withName("page-scope") and "profile-scope") and long sleeps, then dump it with jcmd:
$ jcmd 15020 Thread.dump_to_file -format=json threads.json
15020:
Created C:\...\threads.json
The relevant part of threads.json, shortened:
{
"container": "page-scope/jdk.internal.misc.ThreadFlock$ThreadContainerImpl@51da8ca7",
"parent": "<root>",
"owner": "3",
"threads": [
{
"tid": "36",
"virtual": true,
"state": "WAITING",
"stack": [
"java.base/java.util.concurrent.StructuredTaskScopeImpl.join(StructuredTaskScopeImpl.java:243)",
"TreeDump.profile(TreeDump.java:15)",
...
]
},
{ "tid": "38", "virtual": true, "state": "TIMED_WAITING", ... }
]
},
{
"container": "profile-scope/jdk.internal.misc.ThreadFlock$ThreadContainerImpl@44af33ca",
"parent": "page-scope/jdk.internal.misc.ThreadFlock$ThreadContainerImpl@51da8ca7",
"owner": "36",
"threads": [
{ "tid": "40", "virtual": true, "state": "TIMED_WAITING", ... },
{ "tid": "42", "virtual": true, "state": "TIMED_WAITING", ... }
]
}
The main thread (tid 3) owns page-scope. Its subtask 36 is profile(), waiting in join(), and it owns profile-scope with the two leaf subtasks. With an ExecutorService all these threads would be flat siblings in the executor's container, and you couldn't tell which request started which thread. See Virtual threads for more on Thread.dump_to_file.
API changes between releases
Structured concurrency has been incubating or in preview since JDK 19, and code written for one release often doesn't compile on the next:
-
JDK 19-20 (JEPs 428, 437): incubator module
jdk.incubator.concurrent. -
JDK 21-24 (JEPs 453, 462, 480, 499): preview in
java.util.concurrent, with subclasses as policies andforkreturning aSubtaskfrom 21 on:// JDK 21-24 only; does not compile on JDK 25 try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { Subtask<User> user = scope.fork(() -> findUser(id)); Subtask<Order> order = scope.fork(() -> findLastOrder(id)); scope.join().throwIfFailed(); return new Page(user.get(), order.get()); }ShutdownOnSuccesswas the "first success wins" policy, and timeouts usedjoinUntil(Instant). -
JDK 25 (JEP 505): the redesign shown in this article.
StructuredTaskScopebecame an interface with staticopenmethods, policies becameJoiners, and timeouts moved into the configuration. -
JDK 26 (JEP 525, sixth preview): more adjustments to the joiners. According to the JEP,
Joinergains anonTimeout()method,allSuccessfulOrThrow()returns a list of results instead of a stream of subtasks,anySuccessfulResultOrThrow()is renamedanySuccessfulOrThrow(), and the configuration function becomes aUnaryOperator. Check the Javadoc of the JDK you compile against.
Because of this churn, keep scope-handling code in a few helper methods instead of spreading it through a code base, so that moving to the next JDK means changing a few lines.
Summary
StructuredTaskScopeis a preview API in JDK 25 and 26. Compile withjavac --enable-preview --release 25and run withjava --enable-preview.- Open a scope with try-with-resources,
forksubtasks, calljoin()once, then read results from theSubtaskhandles or from the valuejoin()returns. - Subtasks run on virtual threads. When the joiner decides the outcome, the scope interrupts the remaining subtasks, and
close()waits until they have finished. open()is "all must succeed". Other joiners:allSuccessfulOrThrow,anySuccessfulResultOrThrow,awaitAll,allUntil, or your ownJoinerwith a thread-safeonCompleteand aresult.- Failures surface as
FailedExceptionwith the subtask's exception as the cause. Timeouts fromwithTimeoutsurface asStructuredTaskScope.TimeoutException. - Nested scopes form a tree: cancellation propagates down, failures propagate up, and scoped values are inherited.
- Only the owner thread may fork and join. Getting a result before
join(), forgettingjoin()and closing scopes out of order all throw. - JSON thread dumps from
jcmd <pid> Thread.dump_to_file -format=jsonshow each scope with its parent, owner and threads. - The API changed in almost every release from 19 to 26, so isolate it behind a few methods.