5

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?

Sandip Armal Patil
  • 6,241
  • 21
  • 93
  • 160
Shahul
  • 51
  • 1
  • 3

3 Answers3

10

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.

Community
  • 1
  • 1
ewernli
  • 38,045
  • 5
  • 92
  • 123
2

If the thread dies, so does the reference to the ThreadLocal entry and so your object (assuming there are no other references) will be garbage collected.

As long as the thread lives, so does your object.

You have to assess what the impact is for your object being long-lived.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Thanks bohemian for ur response. So while serving a next request, i will not get the old values from threadlocal (of previous request).. rite? – Shahul May 15 '12 at 06:40
0

You have a memory leak and the ThreadLocal might already be set, the next time your code gets called. ThreadLocals are a bit of a code smell imo.

keuleJ
  • 3,418
  • 4
  • 30
  • 51