Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If not cleared ThreadLocal variable, What will happen?

defined a threadlocal variable in a class to maintain some instances. setting and getting in a recursive method. Somewhat i cant clear the threadlocal variable when the request completes (i have analysed in all other ways. I can't clear threadlocal).

My question is, If i didn't clear threadlocal variable for each request, what will happen? What are the impacts?

like image 902
Shahul Avatar asked May 15 '12 06:05

Shahul


1 Answers

The javadoc says:

after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

For instance, the implementation here is backed by a HashTable that uses weak references for the key. In this case, the key is the thread. If the thread terminates, the entry in the map becomes eligible for garbage collection.

The garbage colleciton might happen only when the system starts running out of memory space. But this consideration applies to all objects in the system: when objects start being reclaimed depend on the GC policy, which is VM specifc and subject to tuning.

This is my view of good and bad usage of thread locals:

  • It is good ot use thread locals if the point is to address a concurrency issue. For instance, avoiding synchronization of an object that is not thread-safe by keeping one copy per thread. Or to address other design issue related to concurrency.

  • It is bad if the point is to "pass a parameter" down the call chain in a cheap way. You should better refactor your code and pass the object down the call chain as a regular method paramter.

  • It is ok to use thread local to store some form of "current" context, e.g. the current request.

like image 127
ewernli Avatar answered Nov 14 '22 23:11

ewernli