I am trying to use ThreadLocal in the Spring Boot application to keep my context data per request. I have been reading on topics such as ThreadLocal may cause memory leak, that such memory leak will cause of "if one of the Servlets or any other Java class from web application creates a ThreadLocal variable during request processing and doesn't remove it after that, copy of that Object will remain with worker Thread and since life-span of worker Thread is more than web app itself, it will prevent the object and ClassLoader, which uploaded the web app, from being garbage collected. This will create a memory leak in Server.".
The question is, if I have the code there to remove ThreadLocal at the end of my request, will it still cause memory leak issue? For example
@Get
public Response read(int id) {
// set in contextLocal
ThreadLocal<MyContext> contextLocal = ThreadLocal.set(new MyContext(id));
// do some operation that may use contextLocal
myProcess.execute();
// clear contextLocal
contextLocal.remove();
}
I was thinking use cases would be:
Will it cause memory leak if everything works fine in current request, that code executed
contextLocal.remove();
, with my request finally returns with 200?Will it cause memory leak if there were exceptions happening during
my Process.execute()
, which code may not reach tocontextLocal.remove();
with my request will return 500? I am not clear on this use case as if my request errors out, that its current working thread should also be ended in JVM which also will end it's attached thread of ThreadLocal, then there wouldn't be memory leak, correct?If current or many requests stuck in processing, in those case all working thread are kept in JVM with their attached ThreadLocal, this might cause memory leak, but such scenario might be very rare..
Any other scenario in real world today that it may still cause memory leak by using ThreadLocal?