Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threadlocal remove?

Tags:

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?

like image 799
Jim Avatar asked Sep 14 '12 12:09

Jim


People also ask

When should ThreadLocal be removed?

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.

How do I delete ThreadLocal?

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).

Can ThreadLocal cause memory leak?

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.

Why is ThreadLocal needed?

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.


1 Answers

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.

like image 96
Amit Deshpande Avatar answered Sep 30 '22 00:09

Amit Deshpande