Java Code Samples

Understanding the concept behind ThreadLocal

Posted in Code samples, Java by Cristian on July 11, 2012

Intro

I was aware of thread local but never had the occasion of really using it until recently.
So I start 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 most used ones)

  • Genuine per-thread context, such as user id or transaction id.
  • Per-thread instances for performance.
About these ads
Tagged with: ,

7 Responses

Subscribe to comments with RSS.

  1. javarevisited said, on July 12, 2012 at 2:14 pm

    well ThreadLocal poses real risk of memory leak specially in managed environment like J2EE or web application if you fail to remove object when web app get stopped or unloaded and lead to OutOfMemoryError in PermGen. But yes if you use it carefully its a great way to achieve thread-safety, I had used ThreadLocal to make SimpleDateFormat threadsafe, let me know if you find it useful.

    • Cristian said, on July 12, 2012 at 3:58 pm

      Indeed if you don’t use it carefully it might cause problems ,mainly on web apps where you need to clean the “thread context’ in a finally.This article just touched idea of thread local.A saw a lot of discussions about the memory leaks caused by this,BUT is not the usage of ThreadLocal is the misusage of it causing the problems.

  2. JavaPins said, on August 7, 2012 at 6:11 pm

    Understanding the concept behind ThreadLocal « Java Code Samples…

    Thank you for submitting this cool story – Trackback from JavaPins…

  3. About Java said, on December 27, 2012 at 1:01 pm

    informative regarding thread.. thanks for sharing.. :)

  4. daveztong said, on October 31, 2013 at 3:05 am

    Explained very well!

  5. nivas said, on November 5, 2013 at 7:14 am

    nice one..

  6. Sajeev said, on December 9, 2013 at 5:30 am

    Good one


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: