Sub topic 15
Moving code from ThreadLocal to ScopedValue
This chapter assumes you know how to declare and bind a ScopedValue with where(...).run(...), and that you have used ThreadLocal with set, get and remove. The earlier chapters on the comparison and on thread behavior cover the background.
When migration fits
A ThreadLocal is a good candidate for migration when it holds context that is set once at the edge of a request and only read afterwards. Typical examples are the current user, a request ID, a tenant, or a trace ID. The ThreadLocal code usually has a try/finally block around the entry point. That block is the scope you will replace.
Before and after
The old version sets the value, runs the work, and must remember to clean up:
public class OldStyle {
static final ThreadLocal<String> USER = new ThreadLocal<>();
public static void main(String[] args) {
USER.set("alice");
try {
handle();
} finally {
USER.remove();
}
}
static void handle() {
System.out.println("Handling request for " + USER.get());
}
}The new version has no cleanup code, because the binding ends when run returns:
public class NewStyle {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> handle());
}
static void handle() {
System.out.println("Handling request for " + USER.get());
}
}The methods that read the value, such as handle, change only in the field they read. Most of the edit happens at the entry point.
Mapping the old operations
| ThreadLocal | ScopedValue |
|---|---|
| `new ThreadLocal<>()` | `ScopedValue.newInstance()` |
| `set(v)` then `try/finally remove()` | `ScopedValue.where(KEY, v).run(...)` |
| `get()` returning `null` when unset | `get()` throws if unbound. Use `isBound()` or `orElse(...)` |
| Set again in a nested block, then restore by hand | A nested `where(...).run(...)` restores the outer value automatically |
Code that tested for null after get() needs an explicit change. Replace the null check with orElse or isBound.
Nested overrides
If your code saved the old value, set a new one, and restored it in a finally block, replace all of that with a nested where. This is the pattern from the nested-scopes chapter. It removes a common bug, which is forgetting to restore the old value on an exception path.
Cases that do not migrate directly
A scoped value is immutable. Some ThreadLocal uses need a different design:
- Mutable state. If a callee calls
setso the caller can see the change, a scoped value cannot do this. Bind an object that is safe to mutate, or return the result from the method. - Per-thread caches. Reusable buffers or formatters tied to a thread are not context. Leave them as
ThreadLocal, or restructure them. - Values that must reach
new Threadworkers. Scoped values are not inherited by plain threads, so a worker that relied onInheritableThreadLocalneeds the value passed in. Alternatively, fork the work with structured concurrency, which shares the bindings.
Version check
Scoped values were a preview API from Java 21 through 24. Compiling and running there needs --enable-preview. They became final in Java 25. Check your target runtime before you migrate a shared library.
Exercise
A method calls USER.set("admin") partway through a request so that later code sees the new user, then calls USER.set(old) in a finally block. How do you express this with ScopedValue?
Show answer
Wrap only the part that needs the admin user in a nested ScopedValue.where(USER, "admin").run(...). The outer binding becomes visible again when the inner run ends, including when it ends with an exception, so the finally block is no longer needed.