Sub topic 15
Moving code from ThreadLocal to ScopedValue
This chapter assumes you know how ThreadLocal works, how ScopedValue.where(...).run(...) binds a value, and how get, isBound, and orElse read it. Here you will convert existing ThreadLocal code, and you will learn which code should stay as it is.
Check the Java version first
Scoped values went through several stages:
| Java release | Status of `ScopedValue` |
|---|---|
| 20 | Incubator module (`jdk.incubator.concurrent`) |
| 21 to 24 | Preview API. You need `--enable-preview`. |
| 25 | Final. No flag is needed. |
On releases 21 to 24, compile and run with the preview flag:
// javac --release 21 --enable-preview Main.java
// java --enable-preview MainThe API changed between previews. In particular, some static helper methods were removed. This chapter uses only where(...), run, call, and the read methods, which are the stable core. If your project targets a long-term-support release older than 25, check your target release before you migrate production code. Preview APIs can change or disappear between releases.
Ask what the ThreadLocal is for
Before you edit anything, find out what role each ThreadLocal plays. Most uses fall into one of three groups.
- Read-only context set once at the edge of a request, such as user, tenant, trace ID, or locale. This is the ideal case for
ScopedValue. - Temporary override of a value, followed by a restore.
ScopedValuehandles this directly through nested binding. - Mutable per-thread state, such as a reusable
StringBuilder, a cachedSimpleDateFormat, or a counter that callees update. This is not whatScopedValueis for.
The basic conversion
Here is a typical ThreadLocal version. The entry point sets the value and must clean up in finally.
public class Before {
private 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 ScopedValue version removes the set, the try/finally, and the remove:
public class After {
private static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(After::handle);
}
static void handle() {
System.out.println("Handling request for " + USER.get());
}
}The read side, USER.get(), stays the same. Only the entry point changes. The binding ends when run returns, even if handle throws, so a forgotten remove() can no longer leak a value into the next request on a pooled thread.
Return values and checked exceptions
If the old code computed something inside the try block, use call instead of run. call returns the result of the operation.
public class CallExample {
private static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) throws Exception {
int length = ScopedValue.where(USER, "alice")
.call(() -> USER.get().length());
System.out.println(length); // 5
}
}On Java 21 to 24, call takes a Callable, so the compiler requires you to handle Exception. That is why main declares throws Exception. Declaring it is harmless on Java 25 as well.
Replacing save and restore with nesting
A common ThreadLocal idiom is to override a value temporarily and put the old one back. It is easy to get wrong.
String previous = USER.get();
USER.set("admin");
try {
runPrivilegedStep();
} finally {
USER.set(previous); // wrong if previous was null: should remove()
}The restore step has a subtle bug. If there was no previous value, set(null) leaves a null entry behind where remove() was needed. With ScopedValue, nesting does the restore automatically:
ScopedValue.where(USER, "admin").run(() -> runPrivilegedStep());When the inner run finishes, the outer binding is visible again. You cannot forget the restore, because there is no restore code.
Handling "not set" correctly
ThreadLocal.get() returns null when nothing was set (unless you used withInitial). ScopedValue.get() throws NoSuchElementException when no binding exists. Review every read site and choose the right replacement:
| Old code | Replacement | Meaning |
|---|---|---|
| `String u = USER.get(); if (u == null) ...` | `USER.isBound()` | Branch on presence |
| `USER.get() != null ? USER.get() : "anon"` | `USER.orElse("anon")` | Default value |
| `Objects.requireNonNull(USER.get())` | `USER.orElseThrow(() -> new IllegalStateException("no user"))` | Fail with your own exception |
| `ThreadLocal.withInitial(() -> "anon")` | `USER.orElse("anon")` at the read site | No per-thread initial value exists |
public class Defaults {
private static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
System.out.println(USER.orElse("anonymous"));
ScopedValue.where(USER, "alice").run(() ->
System.out.println(USER.orElseThrow(
() -> new IllegalStateException("no user"))));
}
}When callees call set
The hard migration case is a callee that writes to the ThreadLocal for its caller to read later. A scoped value is immutable, so this style does not translate. You have three options, in order of preference.
- Return the result. If a method produces data for its caller, make it a return value. This is usually the cleaner design.
- Bind a mutable holder. The binding is immutable, but the object it refers to need not be. For example:
public class Holder {
private static final ScopedValue<java.util.List<String>> AUDIT =
ScopedValue.newInstance();
public static void main(String[] args) {
var log = new java.util.ArrayList<String>();
ScopedValue.where(AUDIT, log).run(() -> {
step("load");
step("save");
});
System.out.println(log); // [load, save]
}
static void step(String name) {
AUDIT.get().add(name);
}
}- Keep the
ThreadLocal. This applies to mutable per-thread state that is not request context.
Other threads need explicit care
ThreadLocal code sometimes relies on InheritableThreadLocal to pass a value to child threads. A plain new Thread(...) or a task submitted to an executor does not inherit scoped value bindings. Inside such a task the value is unbound, and get() throws.
The simplest migration is to read the value in the parent and rebind it in the child:
public class Handoff {
private static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) throws InterruptedException {
ScopedValue.where(USER, "alice").run(() -> {
String user = USER.get(); // capture in the parent
Thread t = new Thread(() ->
ScopedValue.where(USER, user).run(() ->
System.out.println("child sees " + USER.get())));
t.start();
try {
t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
}Structured concurrency (StructuredTaskScope) can pass bindings to forked subtasks automatically. It is still a preview API in Java 25, so using it requires --enable-preview. If your code uses a thread pool with long-lived worker threads, the explicit capture-and-rebind pattern is the one to use. A pooled thread outlives the request, so a value cannot safely follow it.
A migration checklist
- Find every
ThreadLocalfield and label it as context, override, or mutable state. - For context fields, change the field type to
ScopedValue<T>and initialize it withScopedValue.newInstance(). - Replace each
setandremovepair at an entry point withwhere(...).run(...)or.call(...). - Review every
get()for a null check and replace it withisBound,orElse, ororElseThrow. - Search for threads and executors that relied on inheritance, and add explicit capture.
- Remove
withInitialand any save-and-restore code. - Add a test that calls the code outside any binding, to confirm the unbound case behaves the way you intend.
Exercise
A servlet filter sets a ThreadLocal<String> TENANT, calls the rest of the chain, and clears it in finally. A helper deep in the chain does if (TENANT.get() == null) return "default";. Rewrite the helper line after migrating TENANT to a ScopedValue, and explain what happens if you leave the original line unchanged and no binding exists.
Show answer
Replace the line with return TENANT.orElse("default"); (or branch on TENANT.isBound()). If you leave TENANT.get() == null unchanged, an unbound ScopedValue throws NoSuchElementException from get() instead of returning null, so the default branch is never reached and the request fails.
Exercise
A worker callback running on a pooled thread reads USER, which was bound by the thread that submitted the task. After migrating USER to a ScopedValue, the callback throws. Why, and what is the minimal fix?
Show answer
Pooled threads and plain new threads do not inherit scoped value bindings, so USER is unbound in the callback. The minimal fix is to read USER in the submitting thread, capture it in a local variable, and wrap the callback body in ScopedValue.where(USER, captured).run(...).