Today's Question:  What are you most afraid of as a programmer?       GIVE A SHOUT

Technical Article => Programming =>  Java

Use Java ThreadLocal with caution

 Pi Ke     2014-05-06 02:24:38      9,096    0    0

According to Oracle documentation, ThreadLocal is a class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread. In short, ThreadLocal variables are variables belong to a thread, not a class or an instance of a class.

One common use of ThreadLocal is when you want to access some non thread-safe objects in threads without using synchronization mechanisms like synchronized block and locks. These variables will not share states among different threads, so there is no synchronization problem; while at the same since each thread will have only one instance of the ThreadLocal object, it saves memory.

For example, the class below generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

 import java.util.concurrent.atomic.AtomicInteger;

 public class ThreadId {
     // Atomic integer containing the next thread ID to be assigned
     private static final AtomicInteger nextId = new AtomicInteger(0);

     // Thread local variable containing each thread's ID
     private static final ThreadLocal threadId =
         new ThreadLocal() {
             @Override protected Integer initialValue() {
                 return nextId.getAndIncrement();

     // Returns the current thread's unique ID, assigning it if necessary
     public static int get() {
         return threadId.get();

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

Since ThreadLocal will keep a reference to the object it refers to as long as the thread is alive, there is a risk of memory leak in some applications, especially in Java EE applications. As in Java EE applications, to improve the performance, thread pool will be used most probably, this means that a thread will not be terminated when it completes its task, instead it will be returned to the thread pool and wait for another request. This means that if a class which has a ThreadLocal object defined and it is loaded in the thread, the ThreadLocal will never be GCed until the application terminates. This in turn will cause memory leaks. So the best practice is to clean up the ThreadLocal reference by calling ThreadLocal's remove() method.

If you do not clean up when you're done, any references it holds to classes loaded as part of a deployed webapp will remain in the permanent heap and will never get garbage collected. Redeploying/undeploying the webapp will not clean up each Thread's reference to your webapp's class(es) since the Thread is not something owned by your webapp. Each successive deployment will create a new instance of the class which will never be garbage collected.

You will end up with out of memory exceptions due to java.lang.OutOfMemoryError: PermGen space and after some googling will probably just increase -XX:MaxPermSize instead of fixing the bug.

If you do end up experiencing these problems, you can determine which thread and class is retaining these references by using Eclipse's Memory Analyzer.

So be careful when you are using ThreadLocal to ease your work.Otherwise not only your memory but also yourself may be bitten by it.





No comment for this article.


Who slapped the project manager?

By sonic0002
A young Programmer and his Project Manager board a train headed through the mountains on its way to Wichita. They can find no place to sit except for two seats right across the aisle from a young woman and her grandmother. After a while, it is obvious that the young woman and the young programmer a


No other version available yet.