Configuring StructuredTaskScope in Java: Names, Thread Factories and Timeouts
The open(joiner, configOperator) overload in Java 27 and 28: naming a scope for thread dumps, naming subtask threads or running them on platform threads with a ThreadFactory, and withTimeout deadlines that start at open() and end in CancelledByTimeoutException or partial results.
kvi5hnuCode Sprout team member7 min readOn this page
StructuredTaskScope.open() and open(joiner) use a default configuration: subtasks run in new unnamed virtual threads, the scope has no name, and there's no timeout. Two more overloads let you change that:
static <T, R, R_X extends Throwable> StructuredTaskScope<T, R, R_X>
open(Joiner<? super T, ? extends R, R_X> joiner, UnaryOperator<Configuration> configOperator)
static <T> StructuredTaskScope<T, Void, ExecutionException>
open(UnaryOperator<Configuration> configOperator) // default joiner, custom configuration
The configOperator receives the default configuration and returns a modified one. Configuration is immutable, and each method returns a new instance, so calls chain:
try (var scope = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow(),
cf -> cf.withName("trip-quote")
.withThreadFactory(Thread.ofVirtual().name("quote-", 0).factory())
.withTimeout(Duration.ofSeconds(2)))) {
...
}
| Method | Default | Effect |
|---|---|---|
withName(String) | no name | names the scope, shown in JSON thread dumps |
withThreadFactory(ThreadFactory) | unnamed virtual threads | the factory that creates every subtask thread |
withTimeout(Duration) | no timeout | a deadline for the whole scope, counted from open() |
Configuration in action
The demo uses each option. It's the Java 27 preview API (java --enable-preview ScopeConfig.java on Java 27, no flag on Java 28).
import java.time.Duration;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
import java.util.concurrent.ThreadFactory;
public class ScopeConfig {
static String call(String what, int ms) throws InterruptedException {
Thread.sleep(ms);
return what;
}
static long since(long start) { return Math.round((System.nanoTime() - start) / 1e6 / 100.0) * 100; }
public static void main(String[] args) throws Exception {
// 1. Named virtual threads, and a named scope
Set<String> names = new ConcurrentSkipListSet<>();
ThreadFactory quoteThreads = Thread.ofVirtual().name("quote-", 0).factory();
try (var scope = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow(),
cf -> cf.withName("trip-quote").withThreadFactory(quoteThreads))) {
for (String part : List.of("flight", "hotel", "car")) {
scope.fork(() -> {
names.add(Thread.currentThread().getName() + (Thread.currentThread().isVirtual() ? " (virtual)" : ""));
return call(part, 50);
});
}
System.out.println("1. " + scope.join() + " ran on " + names);
}
// 2. A timeout on an all-or-nothing scope
long start = System.nanoTime();
try (var scope = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow(),
cf -> cf.withTimeout(Duration.ofMillis(300)))) {
scope.fork(() -> call("flight", 100));
scope.fork(() -> call("hotel", 2000)); // a hung partner
scope.join();
} catch (ExecutionException e) {
System.out.println("2. after " + since(start) + " ms: " + e.getCause().getClass().getSimpleName());
}
// 3. The deadline starts at open(), not at join()
start = System.nanoTime();
try (var scope = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow(),
cf -> cf.withTimeout(Duration.ofMillis(300)))) {
Thread.sleep(200); // slow validation in the owner
scope.fork(() -> call("flight", 200)); // would be fine on its own
scope.join();
} catch (ExecutionException e) {
System.out.println("3. after " + since(start) + " ms: timed out, though the subtask only had 100 ms");
}
// 4. Best effort within a deadline: allUntil returns whatever finished
start = System.nanoTime();
try (var scope = StructuredTaskScope.open(Joiner.<String>allUntil(s -> false),
cf -> cf.withTimeout(Duration.ofMillis(300)))) {
scope.fork(() -> call("weather", 100));
scope.fork(() -> call("events", 200));
scope.fork(() -> call("reviews", 1000));
List<Subtask<String>> widgets = scope.join();
Set<String> shown = new TreeSet<>();
for (var w : widgets) shown.add(w.state() == Subtask.State.SUCCESS ? w.get() : "(" + w.state() + ")");
System.out.println("4. after " + since(start) + " ms, dashboard shows " + shown + ", cancelled: " + scope.isCancelled());
}
// 5. Subtasks on platform threads
ThreadFactory platform = Thread.ofPlatform().name("price-calc-", 0).factory();
try (var scope = StructuredTaskScope.open(Joiner.<Boolean>allSuccessfulOrThrow(),
cf -> cf.withThreadFactory(platform))) {
scope.fork(() -> Thread.currentThread().isVirtual());
System.out.println("5. subtask on a virtual thread: " + scope.join().getFirst());
}
}
}
Output (times rounded to 100 ms):
1. [flight, hotel, car] ran on [quote-0 (virtual), quote-1 (virtual), quote-2 (virtual)]
2. after 300 ms: CancelledByTimeoutException
3. after 300 ms: timed out, though the subtask only had 100 ms
4. after 300 ms, dashboard shows [(UNAVAILABLE), events, weather], cancelled: true
5. subtask on a virtual thread: false
Names and thread factories
Part 1 gave the scope a name and its subtasks named threads: quote-0, quote-1, quote-2. Thread.ofVirtual().name("quote-", 0) is a builder that numbers threads from 0, and .factory() turns it into a thread-safe ThreadFactory.
Neither name changes behaviour. They pay off when something goes wrong:
- A JSON thread dump (article 17) shows each scope as a container. With
withName("trip-quote")the container is labelled, so in a dump with hundreds of requests you can find the quote scopes and their subtasks at once (article 36). - Thread names appear in logs, stack traces and profilers.
quote-2says much more than an empty name.
The factory can also change what kind of thread runs a subtask. Part 5 used Thread.ofPlatform(), so isVirtual() was false. That's useful for subtasks that do long CPU-bound work or native calls that would hold a virtual thread's carrier (article 14), or to give subtasks a specific priority or daemon status. Virtual threads stay the right default for I/O-bound subtasks.
A thread factory used by a scope must create a new, unstarted thread for each call. The scope starts it. If the factory returns null, fork throws RejectedExecutionException.
Timeouts
withTimeout(duration) gives the scope a deadline. If it passes before the joiner has produced an outcome, the scope is cancelled: subtasks still running are interrupted, and join() wakes up with the joiner's timeout outcome.

What the outcome is depends on the joiner:
- Throwing joiners, which are the default,
allSuccessfulOrThrowandanySuccessfulOrThrow, makejoin()throwExecutionExceptionwith aStructuredTaskScope.CancelledByTimeoutExceptioncause (part 2). With aFunctionoverload, your own exception type is thrown, wrapping the sameCancelledByTimeoutException. allUntilreturns the list of subtasks as usual (part 4). Finished subtasks have their outcome, and those interrupted by the deadline areUNAVAILABLE. That turns a timeout into "best effort within the deadline": the dashboard showed weather and events, and left out the slow reviews widget.- A custom joiner decides for itself in its
timeout()method (article 33).
To tell a timeout apart from a subtask failure, check the cause:
} catch (ExecutionException e) {
if (e.getCause() instanceof StructuredTaskScope.CancelledByTimeoutException) {
return QuoteResult.tooSlow();
}
throw e;
}
The deadline starts at open()
Part 3 is the important subtlety. The timeout was 300 ms, and the only subtask needed 200 ms. But the owner spent 200 ms on validation after opening the scope and before forking, so the subtask only had 100 ms left, and the scope timed out at 300 ms.
The timeout is a deadline for the whole operation, not a per-subtask budget. That's usually what you want: a request handler with a 2-second budget opens the scope with a 2-second timeout and knows the whole fan-out ends within it. But do slow preparation before open(), or account for it in the timeout.
Timeouts and nested scopes
A subtask that opens its own scope can give it a shorter timeout, but nothing makes the inner deadline inherit the outer one automatically. When the outer deadline passes, though, the outer scope interrupts its subtasks, and an interrupted owner's inner join() throws InterruptedException, which cancels the inner scope too. The outer deadline therefore bounds the whole tree (article 35).
Timeouts versus per-call timeouts
A scope timeout is a backstop for the operation. It doesn't replace timeouts on individual network calls. An HTTP client's connect and read timeouts protect each call and free resources early. The scope's deadline guarantees an upper bound on the whole fan-out even when a call ignores its own timeout. Use both.
What's current
open(joiner, UnaryOperator<Configuration>)andopen(UnaryOperator<Configuration>)are the Java 27 (JEP 533) and Java 28 (JEP 543, final) API. Java 25 took aFunction<Configuration, Configuration>, Java 26 switched toUnaryOperator, and Java 27 added the overload that configures a scope without naming a joiner.- On timeout, Java 25 made
join()throwStructuredTaskScope.TimeoutException, whatever the joiner, and Java 26 added anonTimeouthook toJoiner. Java 27 replaced both with the joiner'stimeout()method, which produces the outcome: the built-in throwing joiners throwExecutionExceptionwith aCancelledByTimeoutExceptioncause, andallUntilreturns the subtasks. Thread.Builder.factory()and named virtual-thread builders have been available since Java 21.
Common questions
Does the timeout apply to each subtask or to the whole scope?
To the whole scope, from open() until the outcome. All subtasks share one deadline. A subtask forked late gets less time.
What happens to subtasks that ignore interruption when the deadline passes?
join() still returns at the deadline with the timeout outcome, but close() waits for those subtasks to finish. The block takes longer than the timeout. Make long-running subtasks respond to interruption.
Can I give one slow subtask a longer budget than the others? Not inside one scope. Put the subtasks that need different deadlines in a nested scope with its own timeout, or give the individual call its own client timeout.
Can a scope's configuration be changed after open()?
No. The configuration is fixed when the scope is opened.
Summary
open(joiner, cf -> ...)customizes a scope through an immutableConfiguration:withName,withThreadFactoryandwithTimeout.- Scope names label the scope's container in JSON thread dumps. Thread factories name subtask threads or switch them to platform threads.
- A timeout is one deadline for the whole scope, starting at
open(). When it expires, the scope is cancelled and the joiner's timeout outcome is used. - Throwing joiners report a timeout as
ExecutionExceptionwith aCancelledByTimeoutExceptioncause.allUntilreturns partial results. - Combine scope timeouts with per-call client timeouts.
Practice questions
A handler opens a scope with a 1-second timeout, loads data from the database for 700 ms, and then forks three 400 ms subtasks. What happens?
Answer
The deadline started at open(), so only 300 ms are left when the subtasks start. They're interrupted at the 1-second mark, and join() throws ExecutionException with a CancelledByTimeoutException cause (with a throwing joiner). Load the data before opening the scope, or set a timeout that accounts for it.
A recommendations page should show whatever is available after 250 ms and never fail because of slow sources. Which joiner and configuration fit?
Answer
StructuredTaskScope.open(Joiner.<Item>allUntil(s -> false), cf -> cf.withTimeout(Duration.ofMillis(250))). join() returns every handle at the deadline (or sooner, if all finish), and the page shows the SUCCESS ones and skips the rest. A throwing joiner would turn the deadline into an exception instead.
How can calling code tell whether an ExecutionException from join() was caused by the deadline or by a failing subtask?
Answer
Check the cause: e.getCause() instanceof StructuredTaskScope.CancelledByTimeoutException means the deadline expired. Any other cause is the exception thrown by the failed subtask.
Previous: Exception Handling in Structured Concurrency: ExecutionException, Causes and Custom Exceptions
Next: Writing Custom Joiners in Java: Quorums, Collectors and Your Own Policies

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.