Performance Zone is brought to you in partnership with:

Cristian Chiovari is a Senior Software Engineer specialized in developing enterprise software applications with experience on software integration and messaging. His expertise include helping clients build software using industry best practices, Test Driven Design, Weblogic, Oracle Service Bus , Spring Frameworks, JEE. Performance improvements is something that is really passionate about and considers software development not only his job but also his main hobby. Cristian is a DZone MVB and is not an employee of DZone and has posted 10 posts at DZone. You can read more from them at their website. View Full User Profile

Understanding the concept behind ThreadLocal

05.22.2013
| 10202 views |
  • submit to reddit

Intro

I was aware of thread local but never had the occasion to really use it until recently. So I started digging a little bit on the subject because I needed an easy way of  propagating some user information via the different layers of my web application without changing the signature of each method called.

Small prerequisite info

A thread is an individual process that has its own call stack. In Java, there is one thread per call stack or one call stack per thread. Even if you don’t create any new threads in your program, threads are there running without your knowledge.Best example is whenyou just start  a simple Java program via main method,then you do not implicitly call new Thread().start(),  but the JVM creates a main thread for you in order to run the main method.

The main thread is quite special because it is the thread from which all the other thread will spawn and when this thread is finished, the application ends it’s lifecycle.

In a web application server normally there is  a pool of of threads ,because a Thread is class quite heavyweight to create.All JEE servers (Weblogic,Glassfish,JBoss etc) have a self tuning thread pool, meaning that the thread pool increase and decrease when is needed so there is not thread created on each request, and existing ones are reused.

Understanding thread local

In order to understand better thread local I will show very simplistic implementation of one custom thread local.

package ccs.progest.javacodesamples.threadlocal.ex1;
 
import java.util.HashMap;
import java.util.Map;
 
public class CustomThreadLocal {
 
    private static Map threadMap = new HashMap();
 
    public static void add(Object object) {
        threadMap.put(Thread.currentThread(), object);
    }
 
    public static void remove(Object object) {
        threadMap.remove(Thread.currentThread());
    }
 
    public static Object get() {
        return threadMap.get(Thread.currentThread());
    }
 
}

So you can call anytime in your application the add method on CustomThreadLocal and what it will do is to put in a map the current thread as key and as value the object you want to associate with this thread. This object might be an object that you want to have access to from anywhere within the current executed thread, or it might be an expensive object you want to keep associated with the thread and reuse as many times you want.
You define a class ThreadContext where you  have all information you want to propagate within the thread.

package ccs.progest.javacodesamples.threadlocal.ex1;
 
public class ThreadContext {
 
    private String userId;
 
    private Long transactionId;
 
    public String getUserId() {
        return userId;
    }
 
    public void setUserId(String userId) {
        this.userId = userId;
    }
 
    public Long getTransactionId() {
        return transactionId;
    }
 
    public void setTransactionId(Long transactionId) {
        this.transactionId = transactionId;
    }
 
    public String toString() {
        return "userId:" + userId + ",transactionId:" + transactionId;
    }
 
}

Now is the time to use the ThreadContext.
I will start two threads and in each thread I will add a new ThreadContext instance that will hold information I want to propagate for each thread.

package ccs.progest.javacodesamples.threadlocal.ex1;
 
public class ThreadLocalMainSampleEx1 {
 
    public static void main(String[] args) {
        new Thread(new Runnable() {
            public void run() {
                ThreadContext threadContext = new ThreadContext();
                threadContext.setTransactionId(1l);
                threadContext.setUserId("User 1");
                CustomThreadLocal.add(threadContext);
                //here we call a method where the thread context is not passed as parameter
                PrintThreadContextValues.printThreadContextValues();
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                ThreadContext threadContext = new ThreadContext();
                threadContext.setTransactionId(2l);
                threadContext.setUserId("User 2");
                CustomThreadLocal.add(threadContext);
                //here we call a method where the thread context is not passed as parameter
                PrintThreadContextValues.printThreadContextValues();
            }
        }).start();
    }
}

Notice:
CustomThreadLocal.add(threadContext)  is the line of code where the current thread is associated with the ThreadContext instance
As you will see executing this code the result will be:

userId:User 1,transactionId:1
userId:User 2,transactionId:2

How this is possible because we did not passed as parameter ThreadContext ,userId or trasactionId to printThreadContextValues ?

package ccs.progest.javacodesamples.threadlocal.ex1;
 
public class PrintThreadContextValues {
    public static void printThreadContextValues(){
        System.out.println(CustomThreadLocal.get());
    }
}

Simple enough :)
When CustomThreadLocal.get() is called from the internal map of CustomThreadLocal it is retrived the object associated with the current thread.
Now let’s see the samples when  is used a real ThreadLocal class. (the above CustomThreadLocal class is just to understand the principles behind ThreadLocal class which is very fast and uses memory in an optimal way)

package ccs.progest.javacodesamples.threadlocal.ex2;
 
public class ThreadContext {
 
    private String userId;
    private Long transactionId;
 
    private static ThreadLocal threadLocal = new ThreadLocal(){
        @Override
        protected ThreadContext initialValue() {
            return new ThreadContext();
        }
 
    };
    public static ThreadContext get() {
        return threadLocal.get();
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public Long getTransactionId() {
        return transactionId;
    }
    public void setTransactionId(Long transactionId) {
        this.transactionId = transactionId;
    }
 
    public String toString() {
        return "userId:" + userId + ",transactionId:" + transactionId;
    }
}

As javadoc describes : ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread

package ccs.progest.javacodesamples.threadlocal.ex2;
 
public class ThreadLocalMainSampleEx2 {
 
    public static void main(String[] args) {
        new Thread(new Runnable() {
            public void run() {
                ThreadContext threadContext = ThreadContext.get();
                threadContext.setTransactionId(1l);
                threadContext.setUserId("User 1");
                //here we call a method where the thread context is not passed as parameter
                PrintThreadContextValues.printThreadContextValues();
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                ThreadContext threadContext = ThreadContext.get();
                threadContext.setTransactionId(2l);
                threadContext.setUserId("User 2");
                //here we call a method where the thread context is not passed as parameter
                PrintThreadContextValues.printThreadContextValues();
            }
        }).start();
    }
}

When get is called , a new ThreadContext instance is associated with the current thread,then the desired values are set the ThreadContext instance.
As you see the result is the same as for the first set of samples.

userId:User 1,transactionId:1
userId:User 2,transactionId:2

(it might be the reverse order ,so don’t worry if you see ‘User 2′ first)

package ccs.progest.javacodesamples.threadlocal.ex2;
 
public class PrintThreadContextValues {
    public static void printThreadContextValues(){
        System.out.println(ThreadContext.get());
    }
}

Another very usefull usage of ThreadLocal is the situation when you have a non threadsafe instance of an quite expensive object.Most poular sample I found was with SimpleDateFormat (but soon I’ll come with another example when webservices ports will be used)

package ccs.progest.javacodesamples.threadlocal.ex4;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class ThreadLocalDateFormat {
    // SimpleDateFormat is not thread-safe, so each thread will have one
    private static final ThreadLocal formatter = new ThreadLocal() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("MM/dd/yyyy");
        }
    };
    public String formatIt(Date date) {
        return formatter.get().format(date);
    }
}

Conclusion:

There are many uses for thread locals. Here I describe only two: (I think the most used ones)

  • Genuine per-thread context, such as user id or transaction id.
  • Per-thread instances for performance.
Published at DZone with permission of Cristian Chiovari, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Greg Reiser replied on Wed, 2013/05/22 - 11:01am

Keep in mind that without clearing values from your thread-local when finished, the next time the thread is pulled from the pool, the original values will be there; usually not a desirable scenario.

Cristian Chiovari replied on Wed, 2013/05/22 - 12:41pm in response to: Greg Reiser

Of course....I was going to write part two with an example of cleaning the thread always in a finally clause when it is used in an application server.

Gaurav Goel replied on Wed, 2013/05/22 - 11:58pm

 Nice Explanation :-) Thanks.

Lokesh Gupta replied on Tue, 2013/05/28 - 12:49pm

 I loved the explanation of core concept. I remember that RESTEasy has a similar functionality available through ResteasyProviderFactory. 

Share context data with JAX-RS ResteasyProviderFactory



Cristian Chiovari replied on Tue, 2013/05/28 - 2:24pm in response to: Lokesh Gupta

Nice articles here indeed :http://howtodoinjava.com .Thanks Lokesh for sharing it

Oleksandr Alesinskyy replied on Wed, 2013/05/29 - 6:26am

 Rather lengthy article on a quite trivial matter.

Dave Ztong replied on Wed, 2013/10/30 - 10:16pm

Expained very well...

Rajesh Kannan S replied on Sun, 2014/06/29 - 12:04pm

Explanation was really awesome..


Thank you so much.

I learned the internals of ThreadLocal very well.


Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.