Sub topic 14
Looking Ahead: Structured Concurrency and Scoped Values
Virtual threads make threads cheap. When threads are cheap, you can start many more of them, so you also need clear ways to organize them and to share data with them. The JDK has two newer APIs for this: structured concurrency and scoped values. Both were designed alongside virtual threads. This chapter is a short preview of each one.
Structured Concurrency
Structured concurrency is a way of writing concurrent code in which a task starts subtasks and then waits for all of them in one block of code. A subtask is a smaller piece of work that runs on its own thread. The rule is simple: subtasks cannot outlive the block that started them.
Compare this with an executor. When you call executor.submit(), you get back a Future. It is easy to forget a Future. If one call fails, the other calls keep running and waste work. Structured concurrency fixes this. The main class is StructuredTaskScope, and it ties every subtask to a single scope.
Here is an example written for JDK 25, where the API is a preview feature. A preview feature is fully built, but it can still change. You must turn it on with a flag.
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class OrderPage {
static String fetchUser() throws InterruptedException {
Thread.sleep(100);
return "Ada";
}
static String fetchOrder() throws InterruptedException {
Thread.sleep(150);
return "order #42";
}
public static void main(String[] args) throws InterruptedException {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> user = scope.fork(OrderPage::fetchUser);
Subtask<String> order = scope.fork(OrderPage::fetchOrder);
scope.join(); // waits for both; throws if either one fails
System.out.println(user.get() + " placed " + order.get());
}
}
}Run it with java --enable-preview --source 25 OrderPage.java. Each fork() starts a new virtual thread. If fetchUser throws an exception, the scope cancels fetchOrder, and join() throws. Because the scope is in a try block, it closes on its own, and no thread is left running.
Scoped Values
The chapter on thread locals showed that a ThreadLocal can be changed at any time and can stay around too long. With millions of virtual threads, that wastes memory and makes bugs hard to find.
A scoped value is a value that you bind for one block of code. Binding means attaching a value to a name for a while. Any code called from inside the block can read the value. When the block ends, the value is gone. Nobody can change it partway through. Scoped values became a final, standard feature in JDK 25 (JEP 506), so this example needs no flags.
public class RequestUser {
static final ScopedValue<String> USER = ScopedValue.newInstance();
static void handle() {
System.out.println("Handling request for " + USER.get());
}
public static void main(String[] args) {
ScopedValue.where(USER, "Ada").run(RequestUser::handle);
System.out.println("Bound after run? " + USER.isBound());
}
}This prints Handling request for Ada and then Bound after run? false.
| Feature | ThreadLocal | ScopedValue |
|---|---|---|
| Can be changed after it is set | Yes, with `set()` | No |
| How long it lasts | Until `remove()` or the thread ends | Until the block ends |
| Shared with forked subtasks | Copied only if inheritable | Yes, inside a `StructuredTaskScope` |
The two APIs work together. Subtasks forked inside a StructuredTaskScope can read the scoped values of their parent, with no copying.
Exercise
In the OrderPage example, fetchOrder throws an exception after 50 milliseconds. What happens to fetchUser, and what does main see?
Show answer
The scope cancels the fetchUser subtask by interrupting its virtual thread. Then scope.join() throws an exception that wraps the failure. The println line never runs, and the try block closes the scope, so no subtask keeps running.
Exercise
Why is a scoped value a better fit than a ThreadLocal for passing the current user to code that runs during one request?
Show answer
A scoped value is bound only for the block that handles the request. It cannot be changed partway through, and it goes away when the block ends. A ThreadLocal can be overwritten, and it can leak if nobody calls remove().