When using a ThreadLocal
should I always call remove()
when I am done or when I do set
the old value is replaced anyway so remove
is redundant?
You should always call remove because ThreadLocal class puts values from the Thread Class defined by ThreadLocal. Values localValues; This will also cause to hold reference of Thread and associated objects. the value will be set to null and the underlying entry will still be present.
There is no way to cleanup ThreadLocal values except from within the thread that put them in there in the first place (or when the thread is garbage collected - not the case with worker threads).
A ThreadLocal variable is referenced by its thread and its lifecycle is bound to it. In most application servers, threads are reused via thread pools and are never garbage collected. If the application code does not carefully clear the ThreadLocal variable, it results in a nasty memory leak.
ThreadLocal is useful, when you want to have some state that should not be shared amongst different threads, but it should be accessible from each thread during its whole lifetime. As an example, imagine a web application, where each request is served by a different thread.
Because ThreadLocal
has Map
of currentThread
and value
, Now if you don't remove the value in the thread which was using it then it will create a memory leak.
You should always call remove because ThreadLocal class puts values from the Thread Class defined by ThreadLocal.Values localValues; This will also cause to hold reference of Thread and associated objects.
From the source code of ThreadLocal
the value will be set to null and the underlying entry will still be present.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With