Scrivio Interview library
InternalsFoundations6 min read · updated 12 November 2026

How is ThreadLocal stored internally, and why can it leak memory in thread pools?

A ThreadLocal stores nothing itself: each Thread object has its own ThreadLocalMap, and the ThreadLocal is only the key into it, held by a weak reference while the value is held strongly. A value therefore lives as long as the thread unless we call remove(), and pool threads live as long as the application. If the ThreadLocal itself becomes unreachable, its key is cleared but the value stays until the map happens to clean stale entries during later operations, which is why we always call remove() in a finally block in pooled threads. ThreadLocal.withInitial() supplies a lazy default value.

Why this question is asked

ThreadLocal is behind many things we use every day: Spring's transaction and security context, logging MDC, date formatters cached per thread. It is also behind a whole family of leaks, both memory leaks and data leaks between requests. Interviewers ask about its internals because once we see where the value is actually stored, both kinds of leak become obvious. In this answer, we will recap what a ThreadLocal is for, look at where the value lives, follow the weak and strong references, see how a leak builds up in a thread pool, and finish with remove() and withInitial().

1A Quick Recap of ThreadLocal

A ThreadLocal gives each thread its own copy of a variable. Two threads calling get() on the same ThreadLocal instance each see their own value, and a set() in one thread is invisible to the other. That makes it useful for per-thread context, such as the current user of a request, and for caching objects that are not thread-safe, such as a SimpleDateFormat.

Java
static final ThreadLocal<String> USER = new ThreadLocal<>();
USER.set("alice"); // on thread A
System.out.println(USER.get()); // alice (thread A)
new Thread(() -> System.out.println(USER.get())).start(); // null (a different thread)

2Where the Value Actually Lives

The surprising part is that the ThreadLocal object does not hold the values. Each Thread object has a field, threadLocals, which points to a ThreadLocalMap, a small hash table specialised for this purpose. When we call USER.set("alice"), the ThreadLocal looks up the current thread, gets that thread's map, and stores an entry with the ThreadLocal as the key and "alice" as the value. get() does the same lookup in reverse.

So the ThreadLocal is just a key, and the values are spread across every thread that has used it. This is why access needs no locking: each thread only touches its own map. It is also why the lifetime of a value is tied to the thread, not to the ThreadLocal.

Step throughFrom a thread to its ThreadLocal value
  1. Thread objectpool thread, lives as long as the application
  2. threadLocals fieldthis thread's ThreadLocalMap
  3. Entry arrayopen addressing, one slot per ThreadLocal used
  4. Entry keyWeakReference to the ThreadLocal
  5. Entry valuestrong reference: kept alive by the thread

5 layers, from the top down. Step through them one at a time.

The chain that keeps a value alive runs from the thread, not from the ThreadLocal.

3Weak Keys and Strong Values

Each entry in the map extends WeakReference<ThreadLocal<?>>. A weak reference does not keep its target alive: if nothing else refers to the ThreadLocal object, the garbage collector can collect it and clear the reference. The value, however, is a normal strong field of the entry.

The weak key was chosen to avoid one kind of leak: if a class that created a ThreadLocal is unloaded or the ThreadLocal is dropped, the thread's map does not keep the ThreadLocal object alive forever. But there is a catch: once the key is cleared, the entry becomes stale, a slot with a null key and a value that nobody can reach through the API, yet it is still strongly referenced by the thread. The map removes stale entries only opportunistically, when a later get(), set() or remove() on that thread happens to probe nearby slots or when the map resizes. If the thread never uses ThreadLocals again, the stale value stays.

What the garbage collector can free
SituationThreadLocal objectValue
ThreadLocal still referenced, no remove()KeptKept while the thread lives
ThreadLocal unreachable, no remove()Collected, key clearedKept until a later cleanup probe
remove() calledUnaffectedEntry removed, value can be freed
Thread endsUnaffectedWhole map can be freed

4How a Leak Builds Up in a Thread Pool

In a short-lived thread, none of this matters, because the whole map is freed when the thread ends. Pool threads, such as Tomcat's request threads or an executor's workers, live for the life of the application. So a value set during one task stays in the thread's map after the task finishes, and the next task on that thread starts with it.

That causes two problems. The first is memory: a large object, such as a 5 MB report buffer set on each of 200 request threads, stays alive permanently, 1 GB in total. In application servers that redeploy applications, it is worse: a value whose class came from the old application's class loader keeps the whole class loader and all its classes alive, which is the classic Metaspace leak on redeploy. The second is correctness: a value such as the current tenant or user, left behind by one request, is visible to the next request on the same thread.

5Always Remove in a finally Block

The fix is to make the lifetime explicit. Whoever sets a ThreadLocal in a pooled thread removes it when the unit of work ends, in a finally block so that exceptions cannot skip it.

Java
static final ThreadLocal<RequestContext> CONTEXT = new ThreadLocal<>();
void handle(Request req) {
CONTEXT.set(new RequestContext(req.tenantId(), req.userId()));
try {
process(req);
} finally {
CONTEXT.remove(); // not set(null): remove() deletes the entry itself
}
}

Notice that remove() is better than set(null). set(null) keeps the entry with a null value, while remove() deletes the entry and lets the map reuse the slot. Frameworks follow this rule for us: Spring clears its transaction and security context at the end of each request, which is one reason to use framework context instead of our own ThreadLocals where possible.

6Lazy Defaults With withInitial()

ThreadLocal.withInitial(Supplier) creates a ThreadLocal whose first get() on each thread calls the supplier and stores the result. It is the modern replacement for subclassing ThreadLocal and overriding initialValue().

Java
static final ThreadLocal<DateTimeFormatter> FMT =
ThreadLocal.withInitial(() -> DateTimeFormatter.ofPattern("yyyy-MM-dd"));
FMT.get(); // first call on this thread: supplier runs, value stored
FMT.get(); // later calls: the same instance
FMT.remove();
FMT.get(); // supplier runs again, a fresh value

Notice the example uses DateTimeFormatter, which is immutable and thread-safe, so in real code we would simply share one static instance. Caching per thread only makes sense for objects that are both expensive and not thread-safe, and with virtual threads, where each task has its own thread, even that kind of cache stops paying off.

7Follow-up questions

Why are the keys weak but the values strong?

If the values were weak, they could disappear while the thread still needed them, since often nothing else refers to them. Weak keys protect against the case where the ThreadLocal itself is dropped, but the price is stale entries whose values linger until cleanup, which is why remove() is still required.

Do ThreadLocals work with virtual threads?

Yes, each virtual thread has its own map just like a platform thread. But virtual threads are created per task and there may be millions of them, so ThreadLocals used as per-thread caches create one copy per task. For per-request context, scoped values, final in Java 25, are designed for this case.

Is calling remove() enough if the ThreadLocal is static?

Yes for the value. A static ThreadLocal stays reachable, so its key is never cleared, which makes forgetting remove() worse, not better: the value stays on every pool thread until the next set().

8Conclusion

In this answer, we saw that each Thread holds a ThreadLocalMap, with ThreadLocal objects as weakly referenced keys and values held strongly, so a value lives as long as the thread unless removed. Pool threads live as long as the application, so values outlive their task, causing memory and class-loader leaks and data leaking into the next task. A dropped ThreadLocal leaves a stale entry whose value stays until later cleanup. We always call remove() in a finally block, and we use withInitial() for lazy defaults.

What to say in the interviewAbout 90 seconds aloud

Open with

A ThreadLocal doesn't actually store the values. Every Thread object has its own ThreadLocalMap, and when I call set, the ThreadLocal finds the current thread's map and stores an entry with itself as the key and my object as the value. get does the same lookup.

Then, if they want more

That's why it needs no locking, and also why the value's lifetime is tied to the thread. In the map, the key is held by a weak reference and the value by a normal strong reference.

The weak key means that if the ThreadLocal object becomes unreachable, the GC can collect it and clear the key, but the value is still strongly held by the thread through a stale entry, and the map only cleans those up opportunistically during later get, set or remove calls on that thread.

In a thread pool, threads live as long as the application, so anything I set stays after my task finishes. That leaks memory, for example large buffers or, on redeploy, a whole class loader, and it can leak data, because the next task on that thread sees the old value, like another user's tenant.

So the rule is: whoever sets a ThreadLocal in a pooled thread calls remove in a finally block, and remove rather than set null, because it deletes the entry. For defaults, ThreadLocal.withInitial takes a supplier that runs lazily on the first get in each thread.

About this answer

Last updated
12 November 2026
Versions it names
Java 25
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How is ThreadLocal stored internally, and why can it leak memory in thread pools?": https://scrivio-interview-library.netlify.app/java/threads/eac640a24e/