Home > DeveloperSection > Forums > When and how should I use a ThreadLocal variable?
Felix Pickles
Felix Pickles

Total Post:24

Posted on    July-15-2015 12:14 AM

 Java Java  Thread 

 1 Reply(s)
 586  View(s)
Rate this:
When should I use a ThreadLocal variable? How is it used?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    July-15-2015 8:37 AM

One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object (I'm looking at you, SimpleDateFormat). Instead, give each thread its own instance of the object.

For example:
public class Foo
    // SimpleDateFormat is not thread-safe, so give one to each thread
    private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
        protected SimpleDateFormat initialValue()
            return new SimpleDateFormat("yyyyMMdd HHmm");
    public String formatIt(Date date)
        return formatter.get().format(date);

Since a ThreadLocal is a reference to data within a given Thread, you can end up with classloading leaks when using ThreadLocals in application servers which use thread pools. You need to be very careful about cleaning up any ThreadLocals you get() or set() by using the 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.

Don't want to miss updates? Please click the below button!

Follow MindStick