When and How to Use ThreadLocal in Java

What is ThreadLocal?

In Java, ThreadLocal has been used since JDK 1.2. In multi-threaded programming, there are multiple ways to achieve thread safety via synchronization / locks. ThreadLocal is a different way to achieve thread-safety by providing explicitly a copy of Object to each thread. Since the Object is not shared, there is no requirement of Synchronization. Therefore, it will help the application performance & system scalability improvement.

In a word, ThreadLocal can be associated with Thread scope, all the code which is executed by Thread has access to ThreadLocal variables but two threads can not see other ThreadLocal variables.

When to use ThreadLocal?

When you need a variable’s value to depend on the current thread and it isn’t convenient to attach the value to the thread in other ways, you can consider using ThreadLocal.

  1. If the variable is not thread safe, it can become thread safe by saving it into ThreadLocal.
    For example: Hibernate Session is not thread safe, and can be save into the ThreadLocal. In this case, only the thread owning the Session can access the session object saved in ThreadLocal.
  2. Implement per thread context information like transaction ID

What we should pay attention to?

Since a ThreadLocal is a reference to data within a given Thread, there is a possibility of memory leaks when using ThreadLocals in application servers which use thread pools. Therefore, make sure the thread clean any ThreadLocal variables before exit. ThreadLocal’s remove() and set(null) methods can be used.

If a ThreadLocal variable is not cleaned up before being destroyed, any references it holds to classes loaded as part of a deployed web application will remain in the permanent heap, and will not get garbage collected. Redeploying/undeploying the webapp will not clean up each Thread’s reference the object class since the Thread is not something owned by the new webapp anymore. This will lead to memory leakage and finally java.lang.OutOfMemoryError in the future.

How to use ThreadLocal?

1. Create a ThreadLocal variable
A ThreadLocal variable is generally private static field in Classes and maintain its state inside Thread.

2. To put Object into ThreadLocal

3. Get Object form ThreadLocal

4. Remove object from ThreadLocal

or

Example:

User context to be saved in ThreadLocal

Demo client

Output:
save to thread name: Thread-2
save to thread name: Thread-1
Thread-1 context string: UserContext [contextId=Thread-1]
save to thread name: Thread-0
Thread-0 context string: UserContext [contextId=Thread-0]
Thread-2 context string: UserContext [contextId=Thread-2]

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on RedditShare on StumbleUponEmail this to someoneShare on TumblrDigg this

One thought on “When and How to Use ThreadLocal in Java

  1. Your post is very nice and easily understandable :)
    I have a doubt from your post – “In the example you are explicitly running 3 threads through the run() method with same object. But in real time application, we don’t use explicit threads to run our application. There might be many threads which run to complete a single user request. That means each thread might have some data to be updated to the user session data. But in your example, which ever thread that creates the thread local object has the access to the session object, and only that thread can modify the session data. So what about all other threads that participate to complete the user request. They wont get access to modify the session object..? So how are we resolving this issue.

Leave a Reply to santhosh Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">