Plug ThreadLocal memory leak #1276
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Gemini explains:
Internal Map Structure:
Each Thread object in Java maintains an internal ThreadLocalMap to store the values associated with ThreadLocal instances for that specific thread. This map uses ThreadLocal instances as keys and the stored values as values.
set(null) vs. remove():
When ThreadLocal.set(null) is called, the entry in the ThreadLocalMap associated with the current ThreadLocal instance is updated, setting its value to null. However, the key (the ThreadLocal instance itself) and the entry in the map remain present.
When ThreadLocal.remove() is called, the entire entry (key and value) for that specific ThreadLocal instance is removed from the ThreadLocalMap.
Memory Leak Scenario:
In a thread pool, threads are reused across multiple tasks or requests. If a ThreadLocal value is set and then cleared with set(null), the ThreadLocal instance (and potentially its classloader, if it's an application-specific ThreadLocal) remains referenced within the thread's ThreadLocalMap.
If the application that deployed the ThreadLocal is later undeployed, but the thread from the pool continues to exist, the ThreadLocal instance and its associated classloader can prevent the garbage collection of the undeployed application's classes and resources. This constitutes a memory leak, as the memory used by the undeployed application cannot be reclaimed.
To prevent this memory leak, it is crucial to use ThreadLocal.remove() instead of ThreadLocal.set(null) when you want to clear a ThreadLocal value and ensure proper cleanup. This explicitly removes the entry from the ThreadLocalMap, allowing for proper garbage collection of the ThreadLocal instance and its associated resources.