Digiaru started this conversation 6 months ago.
ThreadLocal Memory Leak in Java Thread Pools
In a web server using thread pools, I store request metadata in a ThreadLocal. Over time memory use grows, even though threads return to the pool. What’s causing this leak?
Digiaru
Posted 6 months ago
ThreadLocal values are tied to threads, and pooled threads persist beyond a request’s lifecycle. If you don’t properly remove the value, the memory (and any chained references) remains live—leaking memory ([turn0search6]). Fix: • Always call threadLocal.remove() at the end of request handling, ideally in a finally block. • For frameworks like Spring MVC, remove ThreadLocal in interceptor or filter cleanup. • Avoid storing large objects in ThreadLocal; use request-scoped or passed parameters instead.