Lesson · Multithreading Fundamentals
ThreadLocal: state that lives on the thread
14 min readThreadLocal
A ThreadLocal is a variable with one value per thread: get() and set() only ever see the calling thread's copy, so nothing is shared and nothing needs a lock. The catch is where the copy lives. The map is on the thread, and pooled threads live a long time, which turns a forgotten cleanup into a leak that reports the wrong user.
The problem: state shared wider than it should be
Some state is shared and should not be: the user for the current request, the transaction in flight, a formatter that only one thread may touch at a time. Passing it through every method signature is honest and verbose, and making it a static field makes it shared by every thread at once.
SimpleDateFormat is the standard example. It is safe for one thread and corrupts its output when two threads format at the same moment, so a static formatter under load produces mangled dates instead of an exception you can trace.
// Broken by the shared field: SimpleDateFormat keeps mutable state while it formats. static final SimpleDateFormat DD_MM = new SimpleDateFormat("dd/MM"); String label(Date when) { return DD_MM.format(when); // two threads in here at once: call it a coin flip }
A field shared by every thread is a decision about every thread, and most request state is nobody else's business.
One variable, one value per thread
ThreadLocal is a variable declaration with per-thread storage. set(v) writes into the calling thread's own map, and get() reads from the same map; another thread calling get() sees its own value or the initial one. There is no sharing, so there is no race, and there is no unlocking anywhere.
ThreadLocal.withInitial(supplier) gives each thread a starting value, created lazily the first time that thread calls get(). remove() deletes the calling thread's entry, and the next get() starts over from the supplier.
One ThreadLocal instance can serve thousands of threads at once. The object is the key; the values belong to the threads.
| Call | What it does | Remember |
|---|---|---|
set(v) | stores v in the calling thread's map | visible only to that thread |
get() | reads the calling thread's value, creating it from the supplier on first call | the lazy creation happens in that thread |
withInitial(supplier) | declares the per-thread starting value | the supplier runs once per thread |
remove() | drops the calling thread's entry | the cleanup you owe a pooled thread |
ThreadLocal does not make anything thread-safe; it removes the sharing that would need the safety.
ThreadLocal lab
ThreadLocalMap: CONTEXT -> (absent)
ThreadLocalMap: CONTEXT -> (absent)
Same ThreadLocal instance, two memories. Neither get() reads the map of the other thread, and nothing here needed a lock.
Call log
Press set(), get() and remove() on either thread: the log remembers which thread ran each call.
accent = T1 · violet = T2 · amber = leaked state · emerald = cleaned up
Where it earns its keep
Frameworks use it to carry context through code that never asked for it: the MDC fields behind logging, the security context of the current request, the transaction bound to the current thread. Each layer reads the same ThreadLocal and gets the value its caller set.
Per-thread buffers are the other classic: a formatter, a builder, a scratch array that one thread reuses instead of allocating. The formatter is safe because it never crosses threads.
- Request context: user, tenant and trace id, read by code three layers below the controller.
- Legacy unsafe utilities: SimpleDateFormat, non-thread-safe builders, per-thread scratch buffers.
- Transaction and security state: frameworks bind the current transaction or principal to the thread doing the work.
- Not for handing work across threads: a value set here does not follow a task into a pool unless you pass it explicitly.
Context that travels on the thread instead of through signatures is the feature; the same property becomes the bug when the thread is reused.
The map lives on the thread
A ThreadLocal holds no value itself. Each Thread owns a ThreadLocalMap, and the ThreadLocal is the key: get() looks the key up in the current thread's map. That is the whole trick, and it explains both the isolation and the timing.
The entry stores its key weakly and its value strongly. If nothing else references the ThreadLocal object, the key can be cleared, so a discarded ThreadLocal does not pin itself in the map. The value in that entry has no such protection.
That asymmetry is the whole story of the next section: a weak key with a strong value means the map can keep the value alive for as long as the thread lives.
| What is held | Reference strength | Consequence |
|---|---|---|
| The key: the ThreadLocal object | weak | if nothing else references it, the key can be cleared |
| The value: whatever set() stored | strong | the object graph behind it stays reachable while the entry lives |
| The entry itself | owned by the thread's map | it survives until remove(), a cleanup pass, or the thread's death |
A ThreadLocal is a key, not a container: every value lives in a map inside the thread that set it.
The leak: the thread outlives the request
In a pool, threads are created once and live as long as the application. If a request sets a value and never removes it, the entry survives the request inside a thread that never dies, and the next request on that thread can read a stranger's context.
The weak key does not save this. The weakness only helps when the ThreadLocal object itself becomes unreachable; a static ThreadLocal is referenced forever, and even a collected key leaves a strong value behind until something cleans the map. Application server heap dumps show the result: request graphs held alive by worker threads, long after the requests ended.
So the rule for pooled threads is remove() in a finally, on the same thread that set the value, before the task returns to the pool. A framework task wrapper does this for its own keys; your keys are your responsibility.
CURRENT.set(user); try { handleRequest(); // anything in here can read CURRENT.get() } finally { CURRENT.remove(); // runs before the worker returns to the pool }
- Replay the same story without the finally: request 1 sets CURRENT to alice on worker-1.
- Request 1 ends. The framework removes its own keys, but this one has no finally block, so the entry stays.
- worker-1 returns to the pool, and request 2 lands on that same thread.
- Request 2 calls get(). The map still holds alice, so a log line, an audit record or a cache key now reports the wrong user.
- The fix is one line before the task returns: remove() in a finally, on the same thread that set the value.
The thread outlives the request; remove() ends the story.
ThreadLocal anatomy · key versus value
the ThreadLocal stores nothing; the thread stores everythingstatic final ThreadLocal<String> CONTEXT
one key object, shared by every thread
Thread · pool-1-thread-1
ThreadLocalMap · a field on the Thread
A WeakReference: a discarded ThreadLocal does not pin itself in the map.
A strong reference: the object graph stays reachable while the entry lives.
Thread · pool-1-thread-2
ThreadLocalMap · a field on the Thread
A WeakReference: a discarded ThreadLocal does not pin itself in the map.
A strong reference: the object graph stays reachable while the entry lives.
get() looks the key up in the map of the calling thread, so two threads read two values from one ThreadLocal object. The weak key keeps the ThreadLocal from pinning itself; the strong value has no such protection.
Pool boundary · these threads outlive every task
Without remove(), the stale value rides along to the next request that lands on this worker.
InheritableThreadLocal and its limits
InheritableThreadLocal copies the parent's value into each child thread at creation time. That timing is the limit: with a thread pool, the threads already exist long before the tasks arrive, so a task submitted later inherits whatever the pool thread was born with, not what the submitting thread holds.
For the same reason, per-thread maps deserve care with virtual threads. The API still works, but millions of threads each carrying per-thread state is memory pressure, which is why newer APIs prefer explicit values passed down a structured scope.
The honest default stays the same in every case: pass the value as a parameter when the code can accept one, and reserve ThreadLocal for context that genuinely cannot travel that way.
- Inheritance happens at thread creation, not at task submission, and pools break that assumption.
- childValue() can transform the copied value, but it cannot fix the timing.
- ScopedValue (a later part of this course) is the structured replacement: the value is bound to a scope, visible to children created inside it, and gone at the end.
Inheritance is a snapshot taken when the thread is born, and pooled threads are born before your task exists.
What to remember
Three rules cover almost everything:
- Per-thread by design: no sharing and no locking; if a value must cross threads, pass it or it will not follow.
- remove() in a finally for anything set on a pooled thread: the thread outlives the request, and the value would too.
- Prefer explicit parameters: ThreadLocal is for framework-style context, not for making a design shorter.
- Weak key, strong value: the key can be collected while the value keeps the graph alive.
Treat ThreadLocal as scoped state with a deadline, and the deadline is the end of the task.
The leak that names the wrong user
A pooled worker sets the request context, the request ends, and nothing removes the entry. Hours later the same worker serves a different request, and a log line, an audit record or a cache key reports the first user's identity. The weak key does not save it, because the value is held strongly and the thread never dies. remove() in a finally, on the same thread that set the value, is the entire fix.
Interview angles
What does a ThreadLocal actually store, and where?+
Nothing itself. Each thread owns a ThreadLocalMap, and the ThreadLocal object is the key into it. set() and get() touch the calling thread's map only, which is why there is no sharing and no locking.
Why does a ThreadLocal leak in a thread pool?+
Pool threads live as long as the application, and a value left in the map stays strongly reachable even though the key is weak. remove() in a finally, before the task returns, clears the entry. It also stops the next request from reading the previous one's context.
Heap dumps make it visible: request graphs kept alive by worker threads. Frameworks wrap their tasks to remove their own keys; the keys your code sets are your responsibility.
What is the difference between initialValue() and withInitial()?+
withInitial(supplier) is the factory that sets the per-thread starting value for you, and it has been on ThreadLocal since Java 8. Either way the value is created lazily, the first time each thread calls get(), so the supplier runs once per thread.
When does InheritableThreadLocal work, and when does it betray you?+
It copies the parent's value into the child at thread creation, which works for threads you create per task. Pools create their threads long before the tasks, so the snapshot is wrong; pass the value explicitly, or use a structured scope instead.
Common misconception: InheritableThreadLocal passes the submitting thread's value to pool tasks.
How do virtual threads change the ThreadLocal story?+
The API still works, but a value per thread stops being cheap when threads number in the millions, so per-thread maps become memory pressure. The direction of travel is explicit parameter passing and structured scopes for context.