Sub topic 14
Why scoped values suit virtual threads
This chapter assumes you know how to declare a ScopedValue and bind it with where(...).run(...). It also assumes you know the basics of ThreadLocal, and that you have seen virtual threads (Thread.ofVirtual() or Executors.newVirtualThreadPerTaskExecutor()). Earlier chapters covered the other differences between the two mechanisms. Here the focus is on cost and fit when a program runs very many threads.
The problem that virtual threads create
A platform thread is a thin wrapper around an operating system thread. It is expensive, so programs keep a small pool of them, often a few hundred. A virtual thread is scheduled by the JVM and is cheap. The intended style is one virtual thread per task, and a server can have hundreds of thousands or millions alive at once.
That changes how you should think about per-thread state. With 200 pooled threads, a ThreadLocal holding a small object costs almost nothing. With a million virtual threads, each one that touches a ThreadLocal allocates its own thread-local map, and each entry holds its own value. Per-thread overhead that was negligible becomes a real part of the heap.
Virtual threads fully support ThreadLocal, so existing code keeps working. The question is whether ThreadLocal is still the right tool when threads are plentiful and short-lived.
Where ThreadLocal costs more under virtual threads
Three costs matter.
- Per-thread storage. Each thread has its own
ThreadLocalMap. Every thread that sets a value pays for the map and the entry, even when all threads hold equal or equivalent data. - Copying on inheritance.
InheritableThreadLocalcopies the parent's values into each new child thread when the child is created. Creating a million threads means a million copies. Because the child's copy is its own, a change made in the child never reaches the parent. - Mutability and cleanup.
ThreadLocal.setcan be called from anywhere, so any code on the thread can change the value. The value also lives untilremove()is called or the thread ends. In a pool, forgettingremove()leaks data into the next task. Virtual threads are not pooled, so this leak is rarer. The lifetime is still not tied to a block of code.
The Java designers also expected virtual threads to be used in the same code that now uses thread-locals for request context, such as the current user, a trace ID, or a transaction. That is the case scoped values were designed to cover.
How scoped values avoid those costs
A scoped value is bound for the duration of a run or call. The binding is immutable and ends when the method returns. This has three consequences for virtual threads.
- No separate copy per child. Because a binding cannot change, a child thread can share the parent's binding instead of copying it. This sharing is available through structured concurrency (
StructuredTaskScope), covered in the previous chapter. The JVM can hand a forked subtask the same bindings without cloning them, and no subtask can modify what its siblings see. - Cheap setup and teardown. Binding adds a link for the duration of the call, and leaving the call removes it. There is no
remove()and no map to clean up. Rebinding in a nested scope also adds one link and discards it afterwards. - Fast reads.
get()looks up the binding through a small per-thread cache, so reading is comparable in speed toThreadLocal.get().
The exact data structures are an implementation detail and may differ between releases. What you can rely on is the contract: a binding is immutable, it is visible to the code run inside the scope, and it disappears when the scope ends.
The diagram contrasts the two models.
A worked example: one binding per virtual thread
The program below starts five virtual threads. Each binds its own user, then calls a method that reads USER without receiving it as a parameter. The bindings are independent, so each thread prints its own user.
import java.util.concurrent.Executors;
public class VirtualRequests {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 5; i++) {
String user = "user-" + i;
executor.submit(() ->
ScopedValue.where(USER, user).run(VirtualRequests::handle));
}
} // close() waits for all submitted tasks
}
static void handle() {
try {
Thread.sleep(50); // the virtual thread may be unmounted here
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
System.out.println(Thread.currentThread().isVirtual()
+ " " + USER.get());
}
}The binding belongs to the virtual thread, not to the carrier (platform) thread that happens to run it. During Thread.sleep, the virtual thread is unmounted and its carrier may run other virtual threads. When it resumes, possibly on a different carrier, USER.get() still returns the value bound for that task. Each line shows true and the matching user. The output order can vary.
On Java 21 to 24, scoped values are a preview API. Compile and run with --enable-preview, for example javac --release 21 --enable-preview VirtualRequests.java and java --enable-preview VirtualRequests. On Java 25 the API is final and no flag is needed. Java 20 offered it only as an incubator feature.
Binding is per thread, not global to the executor
The binding in the example is made inside the task. Binding outside the executor does not carry over:
import java.util.concurrent.Executors;
public class NotShared {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() ->
System.out.println(USER.isBound())); // false
}
});
}
}This prints false. An executor or a plain Thread.ofVirtual().start(...) creates a thread that does not inherit scoped bindings. This matches the earlier new Thread example. Only StructuredTaskScope forks share the bindings of the thread that opened the scope.
If you need the value in an unstructured task, capture it in a local variable and rebind it inside the task, as the first example does with user.
Decision table
| Situation | Prefer | Reason |
|---|---|---|
| Read-only request context (user, trace ID, tenant) used across many layers | `ScopedValue` | Immutable, bounded to the call, cheap to share with forked subtasks |
| Many virtual threads, each needing the same context | `ScopedValue` with `StructuredTaskScope` | No per-thread copy, siblings cannot alter each other's view |
| Per-thread mutable scratch object, such as a reusable buffer or formatter | `ThreadLocal`, but reconsider | Scoped values cannot be modified. With virtual threads, a per-thread cache gives little reuse because threads are short-lived |
| Code that must run on Java 17 or earlier | `ThreadLocal` | Scoped values are not available |
| Third-party code that already reads a `ThreadLocal` | Keep `ThreadLocal` | You cannot make that library read a `ScopedValue` |
The mutable scratch object row deserves attention. Developers often use ThreadLocal to avoid allocating an expensive object such as a SimpleDateFormat. That trick relies on a thread running many tasks. A virtual thread usually runs one task, so you pay to build the object for every task and get no reuse. A shared immutable object, such as DateTimeFormatter, or a small pool is a better fit.
Limits to keep in mind
- Virtual threads do not require scoped values. Nothing breaks if you keep using
ThreadLocal. The motivation is memory and clarity at scale, and you should measure before migrating working code. - Immutability is shallow. The binding cannot be replaced, but if you bind a mutable object, such as an
ArrayList, every reader still sees and can change that same object. Bind immutable data, or accept the sharing deliberately. - Results do not flow back. A scoped value passes data down the call tree. A child cannot write a new value that the parent later reads. Return results through return values or
Futures. - Unbound reads still fail. In a thread that has no binding,
get()throwsNoSuchElementException. UseisBound()ororElsewhen a task might start outside any scope.
Exercise
A service starts one virtual thread per request using Executors.newVirtualThreadPerTaskExecutor(). The main thread binds USER with ScopedValue.where(USER, "alice").run(...) and, inside that scope, submits tasks that call USER.get(). The tasks throw NoSuchElementException. Why does this happen, and give two ways to fix it.
Show answer
The executor creates new threads that do not inherit the bindings of the submitting thread, so USER is unbound inside each task and get() throws. Fix 1: capture the value in a local variable and bind it again inside the task with ScopedValue.where(USER, value).run(...). Fix 2: fork the work with StructuredTaskScope, which shares the opening thread's bindings with its subtasks (the API is preview in Java 21 to 25).
Exercise
Give two reasons a ThreadLocal costs more than a ScopedValue when a program runs a million short-lived virtual threads, each needing the same read-only request context.
Show answer
Each virtual thread that sets a ThreadLocal allocates its own map and entry, so memory grows with the thread count. An InheritableThreadLocal also copies the parent's values into every child at creation. Scoped values bind one immutable value for the call and let forked subtasks share it, with nothing to copy and no remove() call.