RequestScope bean leak in Singleton beans via ScopedTargetProxy
0 reputation · 25 Dec 2024, 01:51 UTC
When injecting Request-scoped beans into long-lived Singleton beans, Spring typically utilizes a ScopedTargetProxy to manage the lifecycle mismatch. While this allows the singleton to reference the proxy, memory leaks can occur if the underlying request context is not properly cleared after the HTTP request completes.
In high-concurrency environments using custom thread pools, the rapid creation and destruction of these proxies can lead to significant GC pressure. If a thread is returned to a pool without the request scope being explicitly closed, references to the request bean may persist in the heap. This is particularly problematic when manual ThreadLocal manipulation is introduced via custom filters.
What specific lifecycle conditions cause the ScopedTargetProxy to fail to release its reference to the target bean during asynchronous execution? How can one verify if the bean destruction callback is failing to trigger when the request scope closes prematurely in a thread pool?