Sub topic 2
What goes wrong with ThreadLocal
This chapter assumes you know core Java syntax, lambdas, and how threads and the call stack relate. You should also know what a static final field is. Basic ThreadLocal experience helps but isn't required.
The previous chapter showed why passing context such as the current user through every method signature gets tedious. ThreadLocal is the traditional fix. It does remove the parameters, but it brings its own problems. Scoped values were designed around those problems, so it's worth seeing each one run.
How ThreadLocal works
A ThreadLocal<T> is a key. Each Thread object holds a private map from ThreadLocal keys to values. When you call get(), Java looks in the current thread's map. When you call set(v), it writes to that same map.
public class Basic {
static final ThreadLocal<String> USER = new ThreadLocal<>();
public static void main(String[] args) {
USER.set("alice");
handle();
}
static void handle() {
System.out.println("Handling request for " + USER.get());
}
}handle() needs no parameter. The cost is that the value is stored on the thread, not on the call. Every problem below follows from that choice.
Problem 1: The value outlives the work
A ThreadLocal value stays in the thread's map until someone calls remove() or the thread dies. Nothing ties it to the method that set it.
Server code usually runs on pooled threads, which are reused for many tasks. A value set by one task is therefore still there when the next task starts.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class LeakDemo {
static final ThreadLocal<String> USER = new ThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(1);
pool.submit(() -> USER.set("alice"));
pool.submit(() -> System.out.println("Next task sees: " + USER.get()));
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
}
}This prints Next task sees: alice. The second task never set a user, but it received the first task's user. In a real service this is a security bug: request B runs with request A's identity.
The standard defense is a try/finally around every set:
USER.set("alice");
try {
handle();
} finally {
USER.remove();
}This works, but nothing forces you to write it. One missed finally, or one code path that throws before it, brings the bug back. The language has no concept of "this value is valid only during this call."
There is also a memory side effect. The map's keys are weak references, but its values are strong. If a value holds a large object, or a class loader in an application server, the thread keeps it alive until remove() runs. Long-lived pool threads make this a known source of memory leaks.
Problem 2: Any code can change the value
ThreadLocal has a public set. Any method that can see the ThreadLocal field can overwrite the value, and the caller won't know.
public class HiddenMutation {
static final ThreadLocal<String> USER = new ThreadLocal<>();
public static void main(String[] args) {
USER.set("alice");
audit();
System.out.println("Caller sees: " + USER.get());
USER.remove();
}
static void audit() {
USER.set("system");
}
}The output is Caller sees: system. The method audit() changed the context for everyone upstream. With a ThreadLocal, you can't tell what USER.get() returns at a given line by reading only the code around it. Any method called earlier might have changed it.
Nesting is the legitimate version of this need. You may want to run one section as admin and then go back to alice. With ThreadLocal you save the old value, set the new one, and restore the old one in a finally. That is more manual bookkeeping, and it is easy to get wrong.
Problem 3: Inheritance copies data and shares mutable state
Plain ThreadLocal values are not visible to child threads. InheritableThreadLocal fixes that: when you create a new thread, it copies the parent's inheritable values into the child.
public class InheritDemo {
static final InheritableThreadLocal<StringBuilder> LOG = new InheritableThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
LOG.set(new StringBuilder("main"));
Thread t = new Thread(() -> LOG.get().append("+child"));
t.start();
t.join();
System.out.println(LOG.get());
}
}This prints main+child. The copy is of the reference, not the object, so parent and child share one mutable StringBuilder. The sharing happens silently.
Inheritance also has costs:
- The copy happens when the thread is created, even if the child never reads the value.
- Each child gets its own map entries, so memory grows with the number of threads.
- Thread pools create threads once and reuse them. A pooled thread keeps the values it inherited at creation time, not the values of the task now running on it.
The last point is the same staleness bug from Problem 1, by another route.
Problem 4: Unbounded lifetime has a per-thread price
Each thread owns its own map. With a few hundred platform threads, that overhead is small. Virtual threads, introduced in Java 21, are cheap enough that an application may create millions of them. They support ThreadLocal, so a million threads can mean a million small maps. Each one may hold a copy of its own data, and each needs cleanup. A design that was acceptable at a few hundred threads gets expensive at that scale.
Summary of the failure modes
| Problem | Cause | Typical symptom |
|---|---|---|
| Stale values | Value lives as long as the thread, not the call | A pooled thread serves request B with request A's data |
| Memory retention | Map values are held strongly until `remove()` | Slow memory growth, class loader leaks |
| Hidden mutation | `set` is public to anyone with the field | `get()` returns a value no nearby code assigned |
| Manual restore | Nesting requires save, set, restore in `finally` | Context not restored after an exception |
| Costly inheritance | Values are copied at thread creation | Extra memory per thread, stale values in pools |
What a better design needs
Reading the table backwards gives a requirement list for a replacement:
- The value should exist only while a specific block of code runs, and disappear automatically when the block ends, including on an exception.
- Code inside the block should be able to read the value but not assign a new one.
- Rebinding for a nested block should be possible, and should end with that block.
- Sharing with child threads should not require copying per-thread maps.
ScopedValue is built to meet these requirements. The chapters that follow show how to declare, bind, and read one.
Exercise
A web server runs requests on a fixed pool of 8 threads. A filter calls USER.set(currentUser) at the start of each request, but it does not call remove() at the end. A later request arrives with no login, and the filter skips set because there is no user. What does the handler see when it calls USER.get(), and why? Give a fix.
Show answer
The handler sees the user from whichever earlier request ran on the same pool thread, because a ThreadLocal value stays in the thread's map until remove() is called or the thread ends, and pooled threads are reused. The anonymous request is treated as that earlier user. The fix is to wrap the request handling in try { ... } finally { USER.remove(); }, so the value is cleared even if the handler throws. A design where the value is bound only for the duration of the call, as with ScopedValue, removes the need for this cleanup.
Exercise
In the InheritDemo program, why does the parent thread print main+child, and what would change if the value type were an immutable String instead of a StringBuilder?
Show answer
InheritableThreadLocal copies the reference to the parent's value into the child thread. Both threads therefore hold a reference to the same StringBuilder, and the child's append is visible to the parent after join(). With an immutable String, the child could not modify the shared object. It could only call set with a new value, which changes the child's own map entry and leaves the parent's value unchanged. Immutable values make sharing safe, which is one reason scoped values carry immutable data.