Video in progress

How does ThreadLocal used together with a thread pool lead to a memory leak or mixed-up data?

Threads in a pool don't die, so a value put into a ThreadLocal lives as long as the thread unless you call remove(). The next request can also see the old value on that same thread.

📖 Answer

ThreadLocal values are actually stored in a ThreadLocalMap inside the Thread object. Tomcat or ExecutorService threads live for hours or days.

private static final ThreadLocal<UserContext> CTX = new ThreadLocal<>();

void handle(Request r) {
    CTX.set(loadContext(r));   // a big object
    service.process();
    // no remove(): the context stays on the thread
}

Two problems:

  • Memory. Every pool thread keeps its last context hanging around. If the context is big, or creates new ThreadLocals inside it, the heap grows.
  • Security. If the next request calls get() without calling set(), it gets another user's data. That is a very bad bug.

On an application server there is one more: when a webapp is redeployed, a value left on the thread holds the old ClassLoader and metaspace leaks. Tomcat logs an explicit warning about this.

The right way is to always clean up in finally:

try {
    CTX.set(loadContext(r));
    service.process();
} finally {
    CTX.remove();
}

In Java 21 with virtual threads, every request gets a new thread, but with millions of virtual threads ThreadLocal also takes a lot of memory. In new code ScopedValue (final in Java 25) is the better option.