Sub topic 14
Why scoped values suit virtual threads
This chapter assumes you know how ScopedValue.where(...).run(...) binds and reads a value, and that you have used ThreadLocal at least once.
The cost of ThreadLocal at scale
A ThreadLocal stores its values in a map owned by each thread. That is cheap when an application has a few hundred platform threads. Virtual threads change the numbers. A server can create one virtual thread per request, which means hundreds of thousands or millions of short-lived threads. Each thread that touches a ThreadLocal gets its own map and its own copy of the data.
Two more problems make this worse:
- Inheritance copies data. An
InheritableThreadLocalcopies its values into every child thread. With many child threads, the copies add up. - Cleanup is manual. A value stays in the thread's map until you call
remove(). On a pooled thread, a forgottenremove()leaks data into the next task.
How scoped values avoid this
A scoped value is not stored per thread as mutable state. The binding exists only while the run call is on the stack, and the runtime removes it when run returns. Nothing needs cleanup, and nothing is copied when a thread is created.
Because the value is immutable, the runtime can safely share one binding with many threads. The per-thread bookkeeping stays small, and the cost of a binding does not grow with the number of virtual threads.
Example: one binding per virtual thread
Each task binds its own user inside its own virtual thread. Nothing is copied from the parent, and nothing needs remove().
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class VirtualDemo {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 5; i++) {
String user = "user-" + i;
executor.submit(() -> ScopedValue.where(USER, user).run(() -> handle()));
}
}
}
static void handle() {
System.out.println(Thread.currentThread().isVirtual() + " " + USER.get());
}
}The output has five lines, each starting with true and ending with a different user. The order can vary between runs.
On Java 21 through 24, scoped values are a preview feature. Compile and run with --enable-preview, for example javac --release 21 --enable-preview VirtualDemo.java and then java --enable-preview VirtualDemo. In Java 25 the feature is final and needs no flag.
Comparison
| Concern | ThreadLocal | ScopedValue |
|---|---|---|
| Mutability | Mutable through `set` | Immutable once bound |
| Lifetime | Until `remove()` or thread exit | The `run` call only |
| Child threads | Copied if inheritable | Shared through structured concurrency |
| Cost with many virtual threads | A map and copies per thread | Small, independent of thread count |
Subtasks
Plain new Thread does not inherit bindings. When you fork subtasks with StructuredTaskScope, the subtasks see the parent's bindings. The scope guarantees that the subtasks finish before run returns, so the binding is never used after it ends. The runtime shares the binding with the subtasks and does not copy it.
Exercise
Why does a ScopedValue cost less than an InheritableThreadLocal when an application creates a very large number of virtual threads?
Show answer
An InheritableThreadLocal copies its values into each child thread's own map, and the values stay there until removed. A ScopedValue binding is immutable and exists only while run is on the stack. The runtime can share it without copying, and it disappears automatically, so the cost does not grow with the number of threads.