Sub topic 14
Looking Ahead: Structured Concurrency and Scoped Values
Virtual threads let you start a thread for every task. Two problems follow from that. The first is keeping track of all those threads, especially when one of them fails. The second is passing data such as "who is the current user" to code running in many threads without the cost of thread locals.
The JDK has two newer APIs for these problems. Structured concurrency groups related threads so they start, fail, and finish together. Scoped values share read-only data with a block of code and the threads it starts. This chapter gives a short, hands-on introduction to both, so you can recognize them and try them out.
What "Preview" Means
A preview feature is a complete API that the JDK ships so developers can try it and give feedback. It is not final yet. Its classes and methods may change or be removed in a later release.
Preview features are off by default. You must turn them on when you compile and when you run. To run a single source file directly, use:
java --enable-preview --source 25 OrderPage.javaTo compile first and then run:
javac --enable-preview --release 25 OrderPage.java
java --enable-preview OrderPageIf you leave out --enable-preview, the compiler reports an error that says the API is a preview API.
The Problem: Loose Tasks
In an earlier chapter you used Executors.newVirtualThreadPerTaskExecutor() to run tasks. Suppose a web page needs two things at once: the user's name and their order count. With an executor, you submit two tasks and get two Future objects. A Future is a handle to a result that will arrive later.
Nothing connects those two tasks to each other. If the first one fails right away, the second keeps running, even though its result is now useless. If the main thread is interrupted, the two tasks do not stop on their own. You have to write that cleanup code yourself, and it is easy to get wrong.
Structured concurrency fixes this with one rule: subtasks live inside a block of code, and they cannot outlive that block. The subtasks are like the body of an if statement. They start and end inside its braces.
Structured Concurrency with StructuredTaskScope
StructuredTaskScope is the class that holds a group of subtasks. A subtask is one piece of work that the scope runs in its own virtual thread. You use the scope in three steps:
- Open a scope in a
try-with-resources block. - Call
forkonce for each subtask. Each fork starts a new virtual thread. - Call
jointo wait. Then read each result.
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class OrderPage {
static String findUser() throws InterruptedException {
Thread.sleep(200); // stands in for a remote call
return "alice";
}
static int fetchOrderCount() throws InterruptedException {
Thread.sleep(300); // stands in for a database query
return 3;
}
public static void main(String[] args) throws InterruptedException {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> user = scope.fork(OrderPage::findUser);
Subtask<Integer> orders = scope.fork(OrderPage::fetchOrderCount);
scope.join(); // waits for both subtasks
System.out.println(user.get() + " has " + orders.get() + " orders");
}
}
}Both calls run at the same time, so the program takes about 300 milliseconds, not 500. Calling user.get() before join() throws an exception, because the result may not exist yet. The scope makes you wait first.
The try block matters. When it ends, close() makes sure no subtask is still running. A subtask can never leak out of the block.
What Happens When a Subtask Fails
StructuredTaskScope.open() with no arguments uses a simple policy: all subtasks must succeed. If any subtask throws, the scope cancels the others and join() throws a StructuredTaskScope.FailedException. Cancel here means the scope interrupts the other subtasks' threads so they stop early.
import java.util.concurrent.StructuredTaskScope;
public class FailFast {
static String slowCall() throws InterruptedException {
Thread.sleep(5_000);
return "never used";
}
static String brokenCall() {
throw new IllegalStateException("service down");
}
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
try (var scope = StructuredTaskScope.open()) {
scope.fork(FailFast::slowCall);
scope.fork(FailFast::brokenCall);
scope.join();
} catch (StructuredTaskScope.FailedException e) {
System.out.println("Failed: " + e.getCause());
}
System.out.println("Took " + (System.currentTimeMillis() - start) + " ms");
}
}The program prints the IllegalStateException and finishes in a few milliseconds. It does not wait five seconds. The slow subtask is interrupted while it sleeps, and the scope waits for it to stop before close() returns.
Other policies exist. For example, you can wait for the first subtask that succeeds and cancel the rest. In the JDK 25 API you pick a policy by passing a StructuredTaskScope.Joiner to open, such as Joiner.anySuccessfulResultOrThrow(). The names of these joiners have changed between previews, so look them up for your JDK version.
The Shape of the Work
This tree shape also helps with debugging. A JSON thread dump, which you saw in the observability chapter, shows forked threads grouped under their scope, so you can see which request each thread belongs to.
Scoped Values: Sharing Data Without Thread Locals
The thread-locals chapter showed that a ThreadLocal gives each thread its own copy of a value. With a million virtual threads you can have a million copies. Any code can also change a thread local at any time, and the value stays until someone removes it.
A scoped value is a variable that holds one value for the duration of a method call. You bind it, meaning you give it a value, and then run some code. Inside that code, and in every method it calls, get() returns the bound value. When the code returns, the binding is gone. Nobody can change the value while it is bound.
public class RequestUser {
private static final ScopedValue<String> USER = ScopedValue.newInstance();
static void handle() {
log("loading profile");
log("rendering page");
}
static void log(String message) {
System.out.println("[" + USER.get() + "] " + message);
}
public static void main(String[] args) throws InterruptedException {
Thread a = Thread.ofVirtual().start(() ->
ScopedValue.where(USER, "alice").run(RequestUser::handle));
Thread b = Thread.ofVirtual().start(() ->
ScopedValue.where(USER, "bob").run(RequestUser::handle));
a.join();
b.join();
System.out.println("Bound in main? " + USER.isBound());
}
}This runs on JDK 25 with no extra flags. Each virtual thread sees its own user, and log never needs a user parameter. The last line prints false, because main never bound USER. Calling USER.get() there would throw a NoSuchElementException.
ThreadLocal and ScopedValue Side by Side
| Question | ThreadLocal | ScopedValue |
|---|---|---|
| Can code change the value? | Yes, with `set` at any time | No, it is read-only while bound |
| How long does the value last? | Until `remove` is called or the thread ends | Only while the `run` or `call` block runs |
| Risk of forgetting cleanup | High, especially with pooled threads | None, the binding ends on its own |
| Shared with child threads | Only `InheritableThreadLocal`, which copies values | Shared with subtasks forked in a `StructuredTaskScope`, with no copying |
| Status in JDK 25 | Standard | Standard (JEP 506) |
Use a scoped value when data flows one way, from a caller down to the code it calls. Request IDs, the current user, and transaction context are common examples. Keep ThreadLocal for cases where code truly needs to change a per-thread value.
Using Both Together
The two APIs work together. When you fork a subtask inside a scope, the subtask sees the scoped values that were bound when the scope was opened. Here findUser reads the request ID even though it runs on a different virtual thread. This example uses structured concurrency, so it needs --enable-preview.
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class Together {
private static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
static String findUser() {
return "alice (request " + REQUEST_ID.get() + ")";
}
static void handleRequest() {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> user = scope.fork(Together::findUser);
scope.join();
System.out.println(user.get());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
ScopedValue.where(REQUEST_ID, "r-42").run(Together::handleRequest);
}
}The output is alice (request r-42). The value is shared, not copied, so this stays cheap even with many subtasks. It is also safe, because no subtask can change the value.
Summary
- Structured concurrency keeps subtasks inside a block. They start with
fork, finish beforeclose, and are cancelled together when one fails. StructuredTaskScopewas a preview API in JDK 25, so turn it on with--enable-previewand expect changes.- A scoped value is bound for one block of code, cannot be changed while bound, and needs no cleanup.
- Forked subtasks see the scoped values bound around their scope.
Exercise
In the FailFast example, why does the program finish in a few milliseconds instead of five seconds?
Show answer
The default policy from StructuredTaskScope.open() requires every subtask to succeed. When brokenCall throws, the scope cancels the other subtask by interrupting its thread. Thread.sleep in slowCall ends early with an InterruptedException, so join() throws FailedException right away and close() has nothing left to wait for.
Exercise
In RequestUser, what happens if you call log("hello") directly from main, outside any ScopedValue.where(...).run(...) block?
Show answer
USER is not bound in main, so USER.get() throws a NoSuchElementException. You could check USER.isBound() first, or use USER.orElse("anonymous") to supply a default.
Exercise
A teammate stores the current user in a ThreadLocal, sets it at the start of each request, and sometimes forgets to call remove(). Which feature from this chapter prevents that mistake, and why?
Show answer
A ScopedValue prevents it. The value is bound only while the run or call block executes and disappears when the block returns, so there is no remove() to forget. Code also cannot change the value while it is bound.