Sub topic 16
Pitfalls and design guidance
This chapter collects the mistakes that show up most often with scoped values and the rules that help you avoid them. It assumes you can declare a ScopedValue, bind it with where(...).run(...), and read it with get, isBound, orElse and orElseThrow. You also need to know how ThreadLocal works. Scoped values are a final feature in Java 25. In Java 21 through 24 they are a preview API, so compile and run with --enable-preview and a matching --release.
Pitfall 1: reading outside a binding
get() on an unbound scoped value throws NoSuchElementException. This is the most common failure. It usually happens when code that normally runs inside a request scope is called from somewhere else, such as a main method, a test, a scheduled job, or a callback.
Choose the read method that matches what "unbound" means in your design:
get()when a missing binding is a programming error and should fail loudly.orElseThrow(supplier)when you want a clearer exception, such asIllegalStateException("No request context").orElse(default)only when a default is a valid answer, such as"anonymous"for a user.isBound()when you need to branch before reading.
Do not sprinkle orElse everywhere to silence the exception. A silent default can hide a missing binding. Authorization code that treats "unbound" as "anonymous" fails safe. Code that treats it as "admin" does not.
Pitfall 2: the binding does not leave the scope
A binding exists only while run (or call) executes. Anything that reads the scoped value later sees the state at that later time, not the state when the code was written.
import java.util.NoSuchElementException;
import java.util.function.Supplier;
public class EscapingScope {
static final ScopedValue<String> USER = ScopedValue.newInstance();
static Supplier<String> lazy;
static Supplier<String> eager;
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> {
String captured = USER.get();
lazy = () -> USER.get(); // reads when called
eager = () -> captured; // value copied now
});
System.out.println(eager.get()); // alice
try {
System.out.println(lazy.get());
} catch (NoSuchElementException e) {
System.out.println("lazy: no binding here");
}
}
}The lazy supplier looks up USER when it runs, and by then the scope has ended. This affects any deferred work: callbacks, CompletableFuture stages, lambdas stored in fields, and iterators or streams consumed after the method returns. If deferred code needs the value, copy it into a local variable while you are still inside the scope, as eager does.
Pitfall 3: assuming other threads inherit the binding
As the earlier chapter on threads showed, a thread made with new Thread does not inherit bindings. The same holds for tasks submitted to an ExecutorService, because a pool worker thread has no connection to the thread that submitted the task. Only the structured concurrency API (StructuredTaskScope) copies bindings to the subtasks it forks. In Java 21 through 24 that API is itself a preview.
For a plain executor, capture the value and bind it again inside the task:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class RebindInTask {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
ScopedValue.where(USER, "alice").run(() -> {
String user = USER.get();
pool.submit(() ->
ScopedValue.where(USER, user).run(() ->
System.out.println("worker sees " + USER.get())));
});
pool.shutdown();
}
}Rebinding by hand is a sign that the work is not structured. If you find yourself doing it in many places, wrap the pattern in one helper, or move the concurrent work to StructuredTaskScope so inheritance is automatic.
Pitfall 4: confusing an immutable binding with an immutable object
A scoped value cannot be reassigned. There is no set. But the object you bind is an ordinary object. If you bind a HashMap or a StringBuilder, any code that can read it can change it, and every nested call and every forked subtask shares that one instance.
import java.util.ArrayList;
import java.util.List;
public class SharedMutable {
static final ScopedValue<List<String>> LOG = ScopedValue.newInstance();
public static void main(String[] args) {
List<String> messages = new ArrayList<>();
ScopedValue.where(LOG, messages).run(() -> {
LOG.get().add("step 1");
helper();
});
System.out.println(messages); // [step 1, step 2]
}
static void helper() {
LOG.get().add("step 2");
}
}This works, but it quietly turns a scoped value back into shared mutable state, which is what you chose scoped values to avoid. If the object is accessed from several threads, you also need it to be thread-safe. Prefer immutable types such as String, records, and List.of(...). When callees must report something back, return it from the method or, if a mutable collector is truly needed, use a thread-safe one and make that decision on purpose.
Pitfall 5: rebinding looks like mutation
An inner where(...).run(...) creates a new binding that shadows the outer one only for the inner call. The outer binding is untouched. A callee therefore cannot use rebinding to send a value upward to its caller. If a method deep in the stack binds USER to "admin", the caller never sees that. Code written with ThreadLocal.set in mind, where the callee changes the value for everyone after it, will not translate directly.
Pitfall 6: hidden dependencies
Scoped values are implicit parameters. That is their benefit and their risk. A method that calls USER.get() has an input that does not appear in its signature. Readers and tests cannot see it.
Use these guidelines to keep the cost low:
- Use a scoped value for context that crosses many layers and is not the method's main subject: the authenticated user, a request ID, a trace span, a tenant, a transaction handle.
- Pass business data as ordinary parameters. If a method computes a price, the item belongs in its signature.
- Keep scoped values
privateor package-private where you can, and expose a small accessor such asRequestContext.currentUser(). This keeps the field out of unrelated code and gives you one place to apply a policy for the unbound case. - Keep the number of scoped values small. Many unrelated scoped values are a sign that a single immutable context record would be clearer.
- Document which methods require a binding, and test them by binding values in the test.
Testing is simple because bindings need no cleanup:
import java.util.NoSuchElementException;
public class UserServiceCheck {
static final ScopedValue<String> USER = ScopedValue.newInstance();
static String greeting() {
return "Hello, " + USER.orElseThrow(
() -> new IllegalStateException("No user bound"));
}
public static void main(String[] args) {
ScopedValue.where(USER, "test-user").run(() ->
System.out.println(greeting())); // Hello, test-user
try {
greeting();
} catch (IllegalStateException e) {
System.out.println("failed as expected: " + e.getMessage());
}
}
}Pitfall 7: migrating without checking how the value is used
Moving from ThreadLocal to ScopedValue is not a mechanical rename. Check each use first:
| Existing `ThreadLocal` usage | What to do |
|---|---|
| Set once at the start of a request, read many times, cleared at the end | Good fit. Replace `set`/`remove` with `where(...).run(...)`. |
| Set, then changed later by callees | Redesign. Return values, or bind a deliberately mutable holder. |
| Per-thread cache, such as a reusable `SimpleDateFormat` | Not a fit. Keep `ThreadLocal` or use a thread-safe alternative. |
| Relies on `InheritableThreadLocal` for child threads | Use `StructuredTaskScope`, or capture and rebind by hand. |
| Needs `remove()` in a `finally` block | Becomes automatic. The binding ends when `run` returns, even on an exception. |
Remember that ThreadLocal still works. With virtual threads, per-thread mutable state is still allowed, but each virtual thread holds its own copy, so a large number of threads with large values costs memory. Scoped values avoid that cost for read-only context. This is the main performance argument for migrating, and it matters most when you create very many virtual threads.
Choosing between the two
Summary checklist
- Decide what "unbound" means for each scoped value and pick
get,orElseThrow,orElseorisBoundto match. - Copy values you need later into locals before leaving the scope.
- Rebind by hand in executor tasks, or use
StructuredTaskScope. - Bind immutable objects.
- Do not rely on a callee changing a binding for its caller.
- Keep scoped values few, narrow in visibility, and limited to cross-cutting context.
Exercise
A service binds USER and then calls executor.submit(() -> audit(USER.get())). In production the task fails with NoSuchElementException. Explain why, and give two ways to fix it.
Show answer
The executor's worker thread did not inherit the submitting thread's bindings, so USER is unbound inside the task. Fix 1: read the value in the submitting thread (String user = USER.get();) and either pass it to audit(user) or bind it again inside the task with ScopedValue.where(USER, user).run(...). Fix 2: do the concurrent work in a StructuredTaskScope, which gives forked subtasks the parent's bindings.
Exercise
You are migrating a ThreadLocal<Integer> named DEPTH that each recursive call increments with set(get() + 1) and decrements on return. Why does a direct switch to ScopedValue not work, and how would you restructure it?
Show answer
A scoped value has no set, and a callee's rebinding does not reach its caller. Instead of mutating, rebind in the recursive call: ScopedValue.where(DEPTH, DEPTH.get() + 1).run(() -> recurse()). The inner scope sees the larger value, and the outer scope sees its own value again when the inner call returns, so no decrement is needed. Alternatively, pass depth as an ordinary parameter, since it is the method's main input.