
Kar started this conversation 4 days ago.
Java Memory Leak: ThreadLocal Values Not Removed in Thread Pools
I use ThreadLocal to store per-request data in a web application with a thread pool. Even after the request completes, memory usage grows continuously. Objects are never garbage collected. What’s causing the leak?
Kar
Posted 4 days ago
ThreadLocal values persist in thread-local maps even after the holding object is done—especially in pooled threads. If you don’t explicitly call .remove(), references linger, leaking memory ([turn0search17]turn0search11]turn0search1]). Fix Options: • Always call threadLocal.remove() inside a finally block once you're done processing. • Avoid storing large, accumulating objects in ThreadLocal. • Use WeakReference or WeakHashMap wrappers if appropriate for cleanup behavior. • Document usage clearly in code comments and enforce cleanup in shared code paths.