The Problems With ThreadLocal in Java: Mutability, Leaks and InheritableThreadLocal
Why ThreadLocal is a poor carrier for context: any code can overwrite it, values outlive their task on pooled threads and leak between requests, and InheritableThreadLocal shares mutable objects, snapshots values at thread creation, and hands pool threads the wrong request's data.
kvi5hnuCode Sprout team member8 min readOn this page
Article 38 showed why frameworks put request context into a ThreadLocal. This article looks at what that costs. The problems all come from three design properties: a thread-local value can be changed by anyone, it lives as long as the thread, and inheritance copies it at thread creation. Scoped values (article 40) were designed to remove all three.
How thread-locals are stored
A ThreadLocal object holds no values itself. Each Thread has a map from thread-local keys to values, and get() looks up the current thread's map.

The map holds its keys weakly but its values strongly. A value therefore stays reachable for as long as the thread is alive, unless someone calls remove(). Even when the ThreadLocal object itself has been garbage collected, the stale entry may stay in the map until a later map operation happens to clean it up.
Six problems in one program
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Solution {
static final ThreadLocal<String> TENANT = new ThreadLocal<>();
static final ThreadLocal<String> USER = new ThreadLocal<>();
static final InheritableThreadLocal<List<String>> TAGS = new InheritableThreadLocal<>();
static final InheritableThreadLocal<String> TRACE = new InheritableThreadLocal<>();
/** A copying variant: each child thread gets its own list. */
static final InheritableThreadLocal<List<String>> COPIED_TAGS = new InheritableThreadLocal<>() {
@Override protected List<String> childValue(List<String> parentValue) {
return new ArrayList<>(parentValue);
}
};
static void someLibraryHelper() {
TENANT.set("admin"); // nothing stops any code from overwriting it
}
static void join(Thread t) throws InterruptedException {
t.join();
}
public static void main(String[] args) throws Exception {
// 1. Unconstrained mutability
TENANT.set("acme");
System.out.println("1. tenant before helper: " + TENANT.get());
someLibraryHelper();
System.out.println(" tenant after helper: " + TENANT.get());
TENANT.remove();
// 2. Unbounded lifetime: a value left behind on a pooled thread leaks into the next task
try (ExecutorService pool = Executors.newFixedThreadPool(1)) {
pool.submit(() -> USER.set("alice")).get(); // forgot USER.remove()
System.out.println("2. next task sees user: " + pool.submit(USER::get).get());
}
// 3. Inheritance copies the reference: parent and child share one mutable list
TAGS.set(new ArrayList<>(List.of("checkout")));
join(Thread.ofPlatform().start(() -> TAGS.get().add("added-by-child")));
System.out.println("3. parent's list now: " + TAGS.get());
COPIED_TAGS.set(new ArrayList<>(List.of("checkout")));
join(Thread.ofPlatform().start(() -> COPIED_TAGS.get().add("added-by-child")));
System.out.println(" with childValue copy: " + COPIED_TAGS.get());
// 4. Inheritance is a snapshot taken when the thread is created
TRACE.set("t-1");
Thread child = Thread.ofPlatform().unstarted(() -> System.out.println("4. child sees trace: " + TRACE.get()));
TRACE.set("t-2");
child.start();
join(child);
// 5. Pool threads inherit from whichever request happened to create them
try (ExecutorService pool = Executors.newFixedThreadPool(1)) {
TRACE.set("request-A");
pool.submit(() -> { }).get(); // the pool's thread is created now
TRACE.set("request-B");
System.out.println("5. B's task sees trace: " + pool.submit(TRACE::get).get());
}
// 6. Virtual threads inherit too, unless the builder turns it off
join(Thread.ofVirtual().start(() -> System.out.println("6. virtual thread: " + TRACE.get())));
join(Thread.ofVirtual().inheritInheritableThreadLocals(false)
.start(() -> System.out.println(" without inheritance: " + TRACE.get())));
}
}
Output:
1. tenant before helper: acme
tenant after helper: admin
2. next task sees user: alice
3. parent's list now: [checkout, added-by-child]
with childValue copy: [checkout]
4. child sees trace: t-1
5. B's task sees trace: request-A
6. virtual thread: request-B
without inheritance: null
1. Anyone can change it
ThreadLocal has a public set(), so any code that can reach the variable can replace the value at any point during the request. Here a helper switched the tenant to admin, and everything after it ran with the wrong tenant. When a value can change anywhere, you can't reason about it locally: you'd have to inspect every method the request calls.
There's no way to give code read-only access to a ThreadLocal. A framework can hide the variable behind a static getter, but its own code, and any code that gets hold of it, can still write.
2. Values outlive their task
On a pooled thread, a value lives until remove() is called, and the thread lives as long as the pool. The first task set alice and didn't clean up, so the next task, from a completely different request, ran as alice. On a real server this is a security bug: one user's identity, tenant or permissions leak into another user's request.
The same property causes memory leaks. A large object stored in a thread-local of a pool thread stays reachable indefinitely. In application servers, a thread-local value whose class came from a web application's class loader keeps the whole class loader alive after the application is undeployed, a classic cause of out-of-memory errors after redeployment.
The rule "always remove() in finally" prevents both, but it relies on every piece of code that calls set() following it.
3. Inheritance shares mutable objects
InheritableThreadLocal copies the parent's values into each child thread when the child is created. It copies references: by default, childValue(parent) returns the parent's object itself. Parent and child then share one ArrayList, so the child's add appeared in the parent's list, and concurrent changes would be a data race.
Overriding childValue to return a copy gives each child its own list, at the cost of copying on every thread creation. For large values and many threads that copying gets expensive, and it must be repeated for every inheritable variable.
4. Inheritance is a one-time snapshot
The child was created while the trace was t-1, and the parent changed it to t-2 before starting the child. The child still saw t-1. Inheritance happens in the Thread constructor, not at start(), and never again, so parent and child silently drift apart.
5. Pools inherit the wrong request's data
Pool threads are created lazily, by whichever thread happens to submit a task when the pool needs a new one. Here the pool's only thread was created during request A, so it inherited request-A, and every later task on it saw request-A, including request B's. InheritableThreadLocal and thread pools don't mix: what a task sees depends on the pool's thread-creation history.
6. Virtual threads inherit too
Virtual threads inherit inheritable thread-locals by default, so every virtual thread created in a request copies the parent's inheritable map. Thread.Builder.inheritInheritableThreadLocals(false) turns this off for threads that don't need it.
Thread-locals and virtual threads
Article 15 covered the memory side: a thread-local cache that was one object per pool thread becomes one object per task when every task gets its own virtual thread. Context thread-locals are cheaper, because each virtual thread holds only references, but each one still needs its own map entries, and inheritance copies them for every child.
To find thread-local use in virtual threads, run with -Djdk.traceVirtualThreadLocals=true. The JVM prints a stack trace whenever a virtual thread sets a thread-local:
VirtualThread[#26]/runnable@ForkJoinPool-1-worker-1
java.base/java.lang.ThreadLocal.set(ThreadLocal.java:231)
Trace.lambda$main$0(Trace.java:2)
java.base/java.lang.VirtualThread.run(VirtualThread.java:460)
What context really needs
The six problems point to what a better mechanism should provide:
| Context needs | ThreadLocal gives |
|---|---|
| a value fixed for a well-defined piece of code | a value anyone can change at any time |
| a lifetime that ends with that code | a lifetime that ends with the thread |
| automatic restoring of outer values in nested code | manual save-and-restore |
| cheap sharing with child tasks that finish first | copying at thread creation, for every child |
That's exactly what ScopedValue provides: immutable bindings, a bounded lifetime tied to a method call, automatic rebinding for nested code, and inheritance without copying into structured subtasks. Article 40 introduces it.
What's current
ThreadLocalandInheritableThreadLocalare unchanged in Java 25 to 27, and remain fully supported. They're still the right tool for some jobs, such as per-thread caches on platform threads.Thread.Builder.inheritInheritableThreadLocals(boolean)has been available since Java 21. An earlier preview option to forbid thread-locals entirely in a thread was removed before Java 21.-Djdk.traceVirtualThreadLocals=trueworks since Java 21 (verified on 21 and 25), and is a quick way to audit libraries before moving to virtual threads.
Common questions
If keys are weak, why do thread-locals leak? Only the key is weak. The value is strongly reachable from the thread's map until the entry is removed, and stale entries are cleaned only opportunistically. A long-lived thread with a forgotten value keeps it indefinitely.
Is ThreadLocal.withInitial safer?
It avoids null checks, but not the problems above. The initial value is created once per thread and then stays for the thread's lifetime like any other value.
Should I use InheritableThreadLocal to pass context to executor tasks?
No. As problem 5 shows, pool threads inherit from whichever thread created them, not from the submitter. Capture the context in the submitting thread and reinstall it in the task, or use structured concurrency with scoped values, which propagate to subtasks correctly.
Can a library protect its thread-local from other code?
Keep the field private and expose only what's needed. That limits who can call set(), but the library's own code paths still have to follow the set-and-remove discipline correctly.
Summary
- Thread-local values are stored in each thread's map, with weak keys and strong values, so they live until
remove()or the thread's death. - Any code can
set()a thread-local, so values can change anywhere in a request. - On pooled threads, a forgotten
remove()leaks values between tasks, a security and memory problem. InheritableThreadLocalcopies references at thread creation: children share mutable objects, miss later changes, and pool threads inherit whichever request created them. Virtual threads inherit by default.- Context needs immutability, a bounded lifetime, automatic nesting and cheap inheritance, which is what
ScopedValueprovides.
Practice questions
A security filter sets the user in a thread-local before calling the servlet and calls remove() afterwards, but not in a finally block. What can go wrong?
Answer
If the servlet throws, remove() is skipped and the user stays on that container thread. The next request handled by the thread starts with the previous user's identity, until something overwrites it. Cleanup must be in finally, or replaced by a mechanism whose lifetime ends automatically.
A parent thread stores a HashMap of feature flags in an InheritableThreadLocal and starts ten child threads, which each add a flag. What's the problem, and how could you fix it?
Answer
All ten children and the parent share the same HashMap, because inheritance copies the reference. Concurrent puts on a HashMap are a data race that can lose entries or corrupt the map. Fix it by making the flags immutable (Map.copyOf), by overriding childValue to return a copy, or by passing the flags as a scoped value, which must be treated as immutable.
Why might a task in a fixed thread pool see an InheritableThreadLocal value from a request that finished an hour ago?
Answer
Pool threads inherit inheritable thread-locals once, when they're created, from the thread that happened to trigger their creation. If an old request caused the pool to create that thread, the thread still carries the old request's value, and every task it runs sees it unless the value is overwritten.
Previous: Passing Context in Java: Parameter Pollution and Why Thread-Locals Were Used
Next: ScopedValue in Java: Binding Context With where(), run() and call()

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.