Sub topic 2
What goes wrong with ThreadLocal
This chapter assumes you know core Java syntax, lambdas, and how threads and the call stack work. A basic familiarity with ThreadLocal helps, but the chapter explains what it needs.
Why people reach for ThreadLocal
Passing a current user or request ID through every method signature gets tedious. A ThreadLocal avoids that. It is a variable with a separate value for each thread, so any code running on that thread can read it without receiving it as a parameter.
public class Basic {
static final ThreadLocal<String> USER = new ThreadLocal<>();
public static void main(String[] args) {
USER.set("alice");
handle();
USER.remove();
}
static void handle() {
System.out.println("Handling request for " + USER.get());
}
}This works, but the design has several weaknesses. They come from the fact that a ThreadLocal is tied to a thread, not to a piece of code.
Problem 1: the lifetime is unbounded
A value set with set stays until someone calls remove or the thread ends. Nothing in the language ties the value to the code that needed it. If you forget remove, the value outlives the request.
This matters most with thread pools, because pool threads are reused for many tasks.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class LeakDemo {
static final ThreadLocal<String> USER = new ThreadLocal<>();
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.submit(() -> USER.set("alice")).get();
pool.submit(() -> System.out.println("Next task sees: " + USER.get())).get();
pool.shutdown();
}
}The second task prints Next task sees: alice, although it never set anything. In a real server this means one user's data can show up in another user's request. The usual defense is a try/finally block around every set, and it fails silently when someone forgets it.
Problem 2: the value is mutable from anywhere
Any code on the thread can call set on the same ThreadLocal. A method deep in the call chain can change the value, and the caller never learns of it. When a bug appears, you cannot tell which code changed the value, because the data flow is hidden. Reading the code of one method no longer tells you what that method will see.
Problem 3: inheritance copies data
A new thread does not see its parent's ThreadLocal values. InheritableThreadLocal addresses this by copying the parent's values into each child thread when the child is created. That has two costs:
- Every child thread holds its own copy, which uses memory.
- The copy happens at thread creation, so a later change in the parent is not seen by the child.
Both costs grow when an application creates many threads.
Problem 4: cost with many threads
Each thread keeps its own map of ThreadLocal values. With a few platform threads this is cheap. Virtual threads can number in the millions, so per-thread storage, plus any inherited copies, becomes a real memory cost. A later chapter returns to this.
Summary of the weaknesses
| Weakness | What happens |
|---|---|
| Unbounded lifetime | Value persists until `remove` or thread death |
| Unrestricted mutation | Any code on the thread can call `set` |
| Costly inheritance | Child threads get copies of the parent's values |
| Per-thread storage | Memory grows with the number of threads |
The next chapters introduce ScopedValue, which removes these problems. A scoped value is bound only for the duration of a call and cannot be changed while it is bound.
Exercise
A web server runs requests on a thread pool and stores the current user in a ThreadLocal. A developer sets the value at the start of each request and never calls remove. Describe what can go wrong, and name one reason that is specific to thread pools.
Show answer
Pool threads are reused, so a value set during one request is still present when the same thread handles a later request. If that later request does not set its own value, it reads the previous user's data, which is both a correctness bug and a security leak. The value also stays reachable for as long as the thread lives, which prevents garbage collection. The fix with ThreadLocal is to call remove in a finally block. ScopedValue avoids the problem because the binding ends when the call ends.