Skip to content

Conversation

Dockerel
Copy link
Contributor

@Dockerel Dockerel commented Jul 3, 2025

Use ThreadLocal.remove() instead of set(null) to prevent memory leak

  • Replaced usages of ThreadLocal.set(null) with ThreadLocal.remove() to properly clear thread-local values.

Previously, ThreadLocal.set(null) was used to clear the ThreadLocal variable. However, this only sets the value to null and leaves an entry in the thread’s local variable map, which can lead to memory leaks. Instead, by using ThreadLocal.remove(), we can properly remove the ThreadLocal variable from the thread's local variable map, preventing memory leaks.

I have reviewed the codebase, and this was the only place where set(null) needed to be replaced with remove().

Let me know if you have any concerns or suggestions for further improvement.
Thank you for your time and consideration!

…leak

Signed-off-by: Giheon Do <dgh0001@naver.com>
@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged label Jul 3, 2025
@wilkinsona wilkinsona changed the title Use ThreadLocal.remove() instead of set(null) to prevent memory leak Use ThreadLocal.remove() instead of set(null) Jul 3, 2025
@wilkinsona wilkinsona added type: task A general task and removed status: waiting-for-triage An issue we've not yet triaged labels Jul 3, 2025
@wilkinsona wilkinsona added this to the 3.4.x milestone Jul 3, 2025
@wilkinsona wilkinsona self-assigned this Jul 3, 2025
@wilkinsona wilkinsona modified the milestones: 3.4.x, 3.4.8 Jul 3, 2025
wilkinsona pushed a commit that referenced this pull request Jul 3, 2025
Signed-off-by: Giheon Do <dgh0001@naver.com>

See gh-46256
@wilkinsona wilkinsona closed this in e3bfc1d Jul 3, 2025
@wilkinsona
Copy link
Member

Thank you, @Dockerel.

FWIW, I don't think there's much risk from a memory leak here. The ThreadLocal in question is only used in a single test and will only ever be accessed on the main thread. That said, it's semantically correct to call remove() rather than set(null) so it was a worthwhile change regardless. Thank again.

@Dockerel Dockerel deleted the fix/threadlocal-remove-instead-of-setnull branch July 3, 2025 07:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: task A general task
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants