Video in progress
With thread pools, how does ThreadLocal lead to a memory leak and mixed-up data?
Threads in a pool don't die, so a value that was never remove()d gets "inherited" by the next task. If the value is a large object or a reference to a class loader, it stays in memory forever.
📖 Answer
A case seen on prod: the logs show one user's request carrying another user's userId. The cause was that the MDC (which is a ThreadLocal too) was filled in a filter but not cleaned up in the error path. The Tomcat thread started the next request with the old context.
The right shape is always the same:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
MDC.put("traceId", resolveTraceId(req));
try {
chain.doFilter(req, res);
} finally {
MDC.clear(); // even if there is an exception
}
}
The memory side: ThreadLocal values live in a map inside the thread object. The key is a weak reference, but the value is a strong one. As long as the thread is alive, the value is alive too. In an application server this was the classic leak when you redeployed an app: the old class loader stayed in memory entirely.
If you need to pass context into tasks submitted to an executor, use Spring's TaskDecorator: it takes a copy on the calling thread, sets it on the worker thread, and cleans up at the end.
Java 21 brought ScopedValue as a preview: the value is bounded by an explicit block, and you can't forget to clean up.
Sign up to mark studied questions and save your progress.