Skip to content
javahacks.dev
Concurrency

Java ThreadLocal Leak Causes and How to Avoid Them

Understand how ThreadLocal leaks memory in thread pools and web apps, how to clean up with remove, and when ScopedValue or explicit parameters are better.

8 min read
Summarize in AI
Flat illustration of threads sharing work across lanes, a lock and a pool, with the OpenJDK, IntelliJ IDEA, Linux and Apache Maven logos.

A ThreadLocal looks like the safest possible way to carry a value through a call stack: each thread gets its own copy, no locks, no sharing. It is how Spring keeps the current transaction, how security frameworks keep the current user and how logging keeps a request id. It is also a reliable source of two bugs that appear only in production: memory that never comes back, and, worse, one request seeing another request's data. Both come from the same fact. Application servers and thread pools reuse threads, so a value set during one request is still there when the next request runs on that thread, unless someone removes it. This post shows the cross-request bug with real output, explains how a ThreadLocal holds memory, the two harms, the fix, the class loader variant that fills metaspace, how to find a leak, the alternatives (including ScopedValue) and what virtual threads change. The output below was produced by running the code on JDK 17.

How it holds memory

Each Thread object has a private map from ThreadLocal keys to values (ThreadLocalMap). threadLocal.set(value) stores the value in the current thread's map; get() reads it. The map belongs to the thread, not the ThreadLocal. The entry stays as long as the thread lives and the key is reachable, and a pooled thread lives as long as the pool, which in a server is the life of the process. Nothing removes the value when the request ends, because the thread does not end; it goes back to the pool.

The map's keys are weak references to the ThreadLocal object, but the values are strong references. If the ThreadLocal itself becomes garbage, the entry's key is cleared, but the value stays referenced from the map until the thread touches the map again and expunges stale entries, which may be never. A value that is large, or that holds a reference to a big object graph, therefore lingers for as long as the thread does.

Two harms, not one

Harm 1: stale data leaks between requests. The following program uses a pool of one thread, so every task runs on the same thread, as happens in practice with many requests and a small pool:

src/main/java/dev/javahacks/tl/TL.javajava
import java.util.concurrent.*;

public class TL {

    static final ThreadLocal<String> USER = new ThreadLocal<>();

    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(1);

        pool.submit(() -> {
            USER.set("ada");
            System.out.println("request 1 sets user=" + USER.get());
        }).get();

        pool.submit(() ->
            System.out.println("request 2 sees user=" + USER.get() + " on " + Thread.currentThread().getName())
        ).get();

        pool.submit(() -> {
            try {
                USER.set("grace");
            } finally {
                USER.remove();
            }
        }).get();

        pool.submit(() -> System.out.println("request 4 sees user=" + USER.get())).get();
        pool.shutdown();
    }
}
Text
request 1 sets user=ada
request 2 sees user=ada on pool-1-thread-1
request 4 sees user=null

Request 2 never set a user and sees ada, left behind by request 1 on the same thread. In a web application that is a security defect: a request that failed to authenticate, or an anonymous one, reads the identity of whoever used the thread last. Request 4 shows the cure: request 3 removed its value in a finally, so the thread was clean. This class of bug is rare in testing, where requests run one at a time on fresh threads, and appears under production load, where threads are reused.

Harm 2: a memory leak. A value that is large, or pinned to something large, stays reachable from the thread. A common version: a SimpleDateFormat or a buffer cached per thread, which is acceptable if bounded, and a per-request object graph (an entity with its lazy collections, a request wrapper) stored and never removed, which leaks every time. The heap shows threads as roots holding retained objects, which is the pattern to look for in a dump, as in debugging a memory leak in a production service.

The fix: set and remove together

The rule is one sentence: whoever calls set must call remove in a finally block at the end of the same scope. Wrap the pair in a small helper so callers cannot forget:

src/main/java/dev/javahacks/tl/RequestContext.javajava
public final class RequestContext {

    private static final ThreadLocal<String> USER = new ThreadLocal<>();

    private RequestContext() { }

    public static String user() {
        return USER.get();
    }

    public static <T> T runAs(String user, java.util.function.Supplier<T> action) {
        String previous = USER.get();
        USER.set(user);
        try {
            return action.get();
        } finally {
            if (previous == null) {
                USER.remove();
            } else {
                USER.set(previous);       // restore, so nested calls compose
            }
        }
    }
}

In a servlet application the natural place is a filter that wraps the whole request:

java
@Component
class UserContextFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws ServletException, IOException {
        RequestContext.runAs(req.getRemoteUser(), () -> {
            try {
                chain.doFilter(req, res);
            } catch (ServletException | IOException e) {
                throw new RuntimeException(e);
            }
            return null;
        });
    }
}

remove() is not the same as set(null): set(null) leaves an entry with a null value in the map, remove() deletes the entry. Prefer remove(). Also clear before use if you cannot trust the previous owner: a defensive remove() at the start of the request handling is cheap insurance in code you do not control. Libraries that manage contexts (Spring's RequestContextHolder, SecurityContextHolder, MDC in logging) clear them in their own filters; the bug usually comes from your own ThreadLocals, and from context set on a pooled thread of an executor that your own code uses. For the MDC, close it with try-with-resources (MDC.putCloseable) or clear in a finally.

The class loader leak

A second, nastier variant ties thread locals to class loaders. In an application server, a long-lived container thread (not owned by your application) runs your code. If your code sets a ThreadLocal whose value, or whose class, comes from your web application's class loader, the container thread's map now references your classes. After you undeploy the application, the thread lives on, still holding the value, which holds your classes, which hold the class loader, which holds every class and static your application loaded. The old application can never be garbage collected, and each redeploy adds another copy. The signature is metaspace growth with each redeploy, ending in OutOfMemoryError: Metaspace. The symptoms and the analysis are in fixing OutOfMemoryError: Metaspace and metaspace leaks from class loaders. Application servers like Tomcat detect and warn: The web application [shop] created a ThreadLocal with key of type [...] but failed to remove it when the web application was stopped. Take that log line seriously; it names the key type. The fix is the same, removing in a finally, plus never storing your own classes in a thread you do not own.

Finding a leak

Evidence before theory. Use the heap dump, as with any leak.

  1. Take a dump of the leaking process (see the leak-hunting post above).
  2. In Eclipse MAT, open the dominator tree and look for large retained sizes under java.lang.Thread objects, then expand a thread's threadLocals field to the ThreadLocalMap$Entry[] table.
  3. For each large entry, read the value's class and "path to GC roots". The class tells you which code stored it.
  4. Search the code for set( on that ThreadLocal, and confirm the matching remove().

Name your threads, which makes the dump readable and lets you tell the pool: naming threads with a ThreadFactory. The memory areas in play, thread stacks and the heap, are explained in JVM memory areas. In a live test, run the same operation thousands of times on a small pool and assert that the thread-local value is null at the start of each task; the first failure tells you which path forgot to remove.

Alternatives

Often the right fix is to not use a ThreadLocal. Pass the value as a parameter, or make it part of an object created per request and passed down. Where a value must flow through code you cannot change, scope it explicitly. Java's ScopedValue (a standard feature in recent JDKs) binds a value for the duration of a call and unbinds it automatically when the call returns, so there is nothing to forget:

java
static final ScopedValue<String> USER = ScopedValue.newInstance();

ScopedValue.where(USER, "ada").run(() -> {
    handle();                       // USER.get() is "ada" in here, and in anything it calls
});
// outside the block, USER is unbound

The value is immutable within the scope, children inherit it cheaply, and it cannot leak past the block because the binding ends with the call. The API is in the [ScopedValue Javadoc](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ScopedValue.html). InheritableThreadLocal is not an improvement: it copies the value into child threads at creation, which spreads the leak.

Virtual threads

Virtual threads support ThreadLocal, and they change the cost of getting it wrong. A virtual thread is created per task and is discarded when the task ends, so a value left behind dies with the thread: the cross-request leak above does not happen when each request gets its own virtual thread. The risk moves. Code that stores something heavy per thread (a cached buffer, a formatter) now stores it per virtual thread, and with a million virtual threads that is a million copies; the per-thread caching idiom stops being a performance optimization and becomes a memory problem. The guidance for virtual threads is to avoid thread-local caching and to prefer ScopedValue for context. The documentation for the class itself is the [ThreadLocal Javadoc](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ThreadLocal.html).

Where this does not apply

A ThreadLocal in a thread you create and end yourself, in a short-lived program, holds nothing past the program's life. A static final thread-local for a thread-unsafe helper such as a formatter, with a small fixed footprint, is a legitimate idiom on platform threads, though DateTimeFormatter is thread-safe and removes the need. And a framework that manages its own context for you (a transaction, a security context) clears it correctly; the bugs are in the ones you add.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.