views:

34

answers:

1

Does any one has an example how to do this? or are they handled by the garbage collector? im using tomcat6

+1  A: 

The javadoc says this:

"Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; 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).

If your application or (if you are talking about request threads) container uses a thread pool that means that threads don't die. If necessary, you would need to deal with the thread locals yourself. The only clean way to do this is to call the ThreadLocal.remove() method.

There are two reasons you might want to clean up thread locals for threads in a thread pool:

  • to prevent memory (or hypothetically resource) leaks, or
  • to prevent accidental leakage of information from one request to another via thread locals.

Thread local memory leaks should not normally be a major issue with bounded thread pools since any thread locals are likely to get overwritten eventually; i.e. when the thread is reused. However, if you make the mistake of creating a new ThreadLocal instances over and over again (instead of using a static variable to hold a singleton instance), the thread local values won't get overwritten, and will accumulate in each thread's threadlocals map. This could result in a serious leak.

Stephen C
thanks for the reply. The problem is that i can only remove the threadlocal once im done with the request. and i have no easy way to know when im done with the request. the way im doing is i have an interceptor at the start of the request that sets the threadlocal (its a static). so i reset it at the start of each request...
Ricardo