0

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:

  1. Will it cause memory leak if everything works fine in current request, that code executed contextLocal.remove();, with my request finally returns with 200?

  2. Will it cause memory leak if there were exceptions happening during my Process.execute(), which code may not reach to contextLocal.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?

  3. 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?

Drex
  • 3,346
  • 9
  • 33
  • 58
  • Your `remove` needs to be in a `finally` block of a `try/finally`. Else it will leak and might be a memory leak or might even leak wrong information to another thread. Espeically in a servlet container where threads are reused. – M. Deinum May 18 '22 at 07:07
  • Yeah that'll be the usual way, however what I have for real use case, there might be several other process between my ThreadLocal set and remove, while it maybe hard to put a try catch finally block from top to bottom.. – Drex May 19 '22 at 04:03
  • As a rule of thumb, where you set it, you also need to clear it. ThreadLocals can be quite dangerous if you don't know how to use them. Why not just pass around the information you need instead of relying on ThreadLocals. – M. Deinum May 19 '22 at 05:13

0 Answers0