Platinum Partner
java,high-perf,tips and tricks,threadlocal,java threadlocal

Understanding the concept behind ThreadLocal

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 {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}