Sub topic 16
Pitfalls and design guidance
This chapter assumes you can declare a ScopedValue, bind it with where(...).run(...), and read it with get, isBound, and orElse. It also assumes you know that ThreadLocal values belong to a thread. Here you will learn the mistakes that cause most scoped value bugs and the rules for deciding when to use the feature.
Pitfall 1: Reading outside a binding
Calling get() when no binding exists throws NoSuchElementException. This usually happens when code that expects a request context runs from a main method, a test, or a scheduled job.
- Use
get()when the value must exist and a missing one is a bug. - Use
orElse(default)when a default is reasonable. - Use
orElseThrow(supplier)when you want a specific exception, such asIllegalStateException("No user bound"). - Use
isBound()only to branch on presence. Do not check it before everyget().
Pitfall 2: Assuming other threads see the binding
A binding exists only for the call stack inside run. A thread made with new Thread, or a task submitted to an ordinary executor, does not inherit it, so USER.isBound() is false there. Bindings reach other threads only through structured concurrency. Subtasks forked in a StructuredTaskScope see the bindings of the thread that opened the scope. That API was still a preview feature in the releases that finalize scoped values, so check your Java version.
If you need a value in an unstructured thread, pass it as an argument or bind it again inside that thread.
Pitfall 3: Confusing an immutable binding with an immutable object
The binding cannot change. There is no set method. The object it refers to can still be mutable.
import java.util.ArrayList;
import java.util.List;
public class MutableTrap {
static final ScopedValue<List<String>> AUDIT = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(AUDIT, new ArrayList<>()).run(() -> {
record("login");
record("search");
System.out.println(AUDIT.get()); // [login, search]
});
}
static void record(String event) {
AUDIT.get().add(event);
}
}This compiles and runs. It also brings back hidden shared state, which is the problem scoped values are meant to avoid. If several threads could reach the list, you would need to make it thread-safe. Prefer immutable values such as strings, records, and List.of(...).
Pitfall 4: Using scoped values as a hidden parameter list
Anything you can pass as an argument should usually be an argument. Explicit parameters are visible in signatures and easy to test. Scoped values suit context that cuts across many layers, such as the current user, a request ID, or a tenant.
Choosing between the options
| Situation | Better choice |
|---|---|
| One or two levels of calls need the data | Method parameter |
| Many layers need read-only request context | `ScopedValue` |
| Callee must change the value for the caller to read | `ThreadLocal`, or return a result instead |
| Value must outlive one call, or be set at any time | `ThreadLocal` |
| Many virtual threads each need context | `ScopedValue` |
Migration guidance
Move a ThreadLocal to a ScopedValue only when its usage is "set at the start, read many times, clear at the end." Find the place where the code calls set and the matching remove, and replace that pair with one where(...).run(...). If the code calls set again in the middle of a request, use nested where calls or keep the ThreadLocal.
Exercise
A servlet filter binds USER with where(USER, name).run(chain). A controller submits work to a shared ExecutorService, and the task calls USER.get(). What happens, and how do you fix it?
Show answer
The task runs on a pool thread that has no binding, so get() throws NoSuchElementException. Fix it by passing the user to the task as an argument, or by rebinding inside the task with ScopedValue.where(USER, name).run(...). You can also use StructuredTaskScope so the forked subtasks inherit the binding.