Threadlocal remove?

Jim picture Jim · Sep 14, 2012 · Viewed 20.6k times · Source

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?

Answer

Amit Deshpande picture Amit Deshpande · Sep 14, 2012

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.