The 30 second answer
A ThreadLocal gives each thread its own copy of a variable, so threads never share it and need no locking. The values really live in a map inside each Thread object: the ThreadLocal is the key, held weakly, and the value is held strongly. I use it for request context such as a request ID, and I always call remove in a finally block, because pool threads are reused and would otherwise leak memory and data.
The problem it solves. Sometimes every thread needs its own copy of a variable, such as the ID of the request it is handling, the logged-in user, or a formatter that is not thread-safe. Passing that value through every method signature is noisy, and one shared field would need synchronization and would mix up requests. A ThreadLocal gives each thread its own private value behind one shared object, so no locking is needed: thread A calling set("req-1") never changes what thread B reads with get().
How it works internally. The values are not stored in the ThreadLocal object. Each Thread object has its own field, threadLocals, which holds a small hash map called ThreadLocalMap (there is a second one, inheritableThreadLocals, for inheritable values). When you call get() or set(), the ThreadLocal looks up the current thread's map and uses itself as the key. In OpenJDK 21 each entry holds the key through a WeakReference to the ThreadLocal instance, and the value through an ordinary strong reference. So one ThreadLocal object can be a key in many threads' maps at once, each with a different value, and the value lives as long as the thread lives unless it is removed. The Javadoc puts it this way: each thread holds an implicit reference to its copy as long as the thread is alive and the ThreadLocal instance is accessible.
A simple example: a request ID per thread. Two worker threads each set a request ID, and a logging method reads it without receiving it as a parameter. A child thread shows how InheritableThreadLocal behaves. I ran this program on OpenJDK 21:
public class RequestIdDemo {
// One ThreadLocal object, shared by all threads.
// Each thread that calls set() gets its own separate value.
static final ThreadLocal<String> REQUEST_ID = new ThreadLocal<>();
// A plain InheritableThreadLocal: child threads get a copy at creation time.
static final InheritableThreadLocal<String> TENANT = new InheritableThreadLocal<>();
static void logLine(String message) {
// No parameter passing: any method on this thread can read the ID.
System.out.println("[" + REQUEST_ID.get() + "] "
+ Thread.currentThread().getName() + ": " + message);
}
static void handleRequest(String requestId) {
REQUEST_ID.set(requestId);
try {
logLine("started");
logLine("finished");
} finally {
REQUEST_ID.remove();
}
}
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(() -> handleRequest("req-1"), "worker-A");
Thread b = new Thread(() -> handleRequest("req-2"), "worker-B");
a.start(); b.start();
a.join(); b.join();
System.out.println("main thread sees: " + REQUEST_ID.get()); // null
TENANT.set("tenant-de");
REQUEST_ID.set("req-3");
Thread child = new Thread(() -> System.out.println(
"child sees tenant=" + TENANT.get() + ", requestId=" + REQUEST_ID.get()), "child");
TENANT.set("tenant-fr"); // changed after the child was created
child.start();
child.join();
System.out.println("parent now has tenant=" + TENANT.get());
}
}Output on OpenJDK 21 (the lines from worker-A and worker-B can interleave differently on each run):
[req-1] worker-A: started
[req-1] worker-A: finished
[req-2] worker-B: started
[req-2] worker-B: finished
main thread sees: null
child sees tenant=tenant-de, requestId=null
parent now has tenant=tenant-frThe common pitfalls. First, forgetting remove() in a thread pool: pool threads are reused for many tasks and live as long as the process, so a value that is never removed stays in memory and is visible to the next task on that thread. The leak demo below shows both effects. Second, InheritableThreadLocal copies values from the parent to a child thread only when the child thread is created. The output shows the child got "tenant-de", the value at creation time, not the later "tenant-fr", and a plain ThreadLocal such as the request ID is not inherited at all. Pool threads are created once and reused, so with an executor the inherited value is whatever happened to be set when the pool created that thread, not the value of the task that submitted the work. Pass context to pooled tasks explicitly instead. Third, logging context such as SLF4J's MDC is backed by thread-local storage, so it needs the same cleanup at the end of each request. Fourth, in application servers that redeploy web apps, a leftover thread-local value whose class came from the old web app can keep that whole class loader, and all its classes, from being unloaded.
Seeing the leak in code. Inside every thread, ThreadLocal values live in a ThreadLocalMap. In OpenJDK 21 its entry class extends WeakReference<ThreadLocal<?>> and keeps the value in a plain Object value field, so the key is weak but the value is strong. The OpenJDK source comment adds that, because no reference queue is used, stale entries are guaranteed to be removed only when the table starts running out of space. Part 1 of the program rebuilds that entry shape: after the key goes out of scope and GC runs, the key reads null, but the 10 MB value is still reachable from the entry, which in a real thread is reachable from the Thread object itself. Parts 2 and 3 run two requests on the same pooled thread, first without cleanup and then with remove() in a finally block.
import java.lang.ref.WeakReference;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadLocalLeakDemo {
// Part 1: how ThreadLocalMap stores an entry.
// The key (the ThreadLocal) is weak; the value is strong.
static class Entry extends WeakReference<Object> {
Object value; // strong reference
Entry(Object threadLocalKey, Object value) {
super(threadLocalKey); // weak reference to the key
this.value = value;
}
}
static void weakKeyStrongValue() throws InterruptedException {
Object threadLocalKey = new Object(); // stands in for a ThreadLocal
Entry entry = new Entry(threadLocalKey, new byte[10_000_000]);
threadLocalKey = null; // the ThreadLocal goes out of scope
for (int i = 0; i < 5 && entry.get() != null; i++) {
System.gc();
Thread.sleep(50);
}
System.out.println("key after GC: " + entry.get()); // null
System.out.println("value after GC: "
+ ((byte[]) entry.value).length + " bytes still reachable");
}
// Parts 2 and 3: a pooled thread reused across tasks.
static final ThreadLocal<String> CURRENT_USER = new ThreadLocal<>();
static void handleWithoutCleanup(String user) {
if (user != null) {
CURRENT_USER.set(user);
}
System.out.println(" without remove(): request sees user = " + CURRENT_USER.get());
}
static void handleWithCleanup(String user) {
try {
if (user != null) {
CURRENT_USER.set(user);
}
System.out.println(" with remove(): request sees user = " + CURRENT_USER.get());
} finally {
CURRENT_USER.remove(); // the fix
}
}
public static void main(String[] args) throws Exception {
System.out.println("1) Weak key, strong value");
weakKeyStrongValue();
ExecutorService pool = Executors.newSingleThreadExecutor(); // one reused thread
System.out.println("2) Before the fix: alice's request, then an anonymous request");
pool.submit(() -> handleWithoutCleanup("alice")).get();
pool.submit(() -> handleWithoutCleanup(null)).get(); // stale "alice"
pool.submit(CURRENT_USER::remove).get(); // reset for part 3
System.out.println("3) After the fix: the same two requests");
pool.submit(() -> handleWithCleanup("alice")).get();
pool.submit(() -> handleWithCleanup(null)).get(); // null
pool.shutdown();
}
}Output on OpenJDK 21:
1) Weak key, strong value
key after GC: null
value after GC: 10000000 bytes still reachable
2) Before the fix: alice's request, then an anonymous request
without remove(): request sees user = alice
without remove(): request sees user = alice
3) After the fix: the same two requests
with remove(): request sees user = alice
with remove(): request sees user = nullSystem.gc() is only a request, so the demo retries it a few times; on OpenJDK 21 the weak key was cleared on the first try. How this ties to the interview answer: a ThreadLocal leak is really two bugs from one cause. The memory bug is that the map's key is weak but its value is strong, so in a pool whose threads live as long as the process, values that are never removed stay in memory even after nobody can read them. The correctness bug is that the next task on the same thread inherits the previous task's value, which is exactly what part 2 shows when the anonymous request sees "alice". The fix is the same for both: every set() is paired with remove() in a finally block, ideally in one place such as a servlet filter or an interceptor, so no handler can forget it.
When to use it, and when not to. Use it for per-request context that many layers need, such as a request or trace ID, the security context or logging MDC, which frameworks already manage this way, and for per-thread reuse of an expensive object that is not thread-safe. Always set it and remove it in one place, such as a filter or interceptor with a finally block. Do not use it to pass ordinary business data between your own methods, where a parameter is clearer and easier to test. Do not rely on it across thread boundaries such as CompletableFuture stages, executors or reactive pipelines, where the work may run on another thread. Avoid storing large objects in it when you run very many virtual threads, because each thread gets its own copy. On Java 25 and later, scoped values (JEP 506) are a bounded, immutable alternative for passing context down a call.
Sources (9)
- ThreadLocal Javadoc (Java 21)docs.oracle.com
- InheritableThreadLocal Javadoc (Java 21)docs.oracle.com
- OpenJDK 21 Thread source (threadLocals and inheritableThreadLocals fields)github.com
- OpenJDK 21 ThreadLocal source (ThreadLocalMap.Entry: weak key, strong value)github.com
- JEP 506: Scoped Values (final in JDK 25)openjdk.org
- WeakReference Javadoc (Java 21)docs.oracle.com
- System.gc Javadoc (Java 21)docs.oracle.com
- JEP 444: Virtual Threads (thread-local variables)openjdk.org
- SLF4J MDC Javadocslf4j.org