Understanding the concept behind ThreadLocal

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.

Reference: Understanding the concept behind ThreadLocal from our JCG partner Cristian Chiovari at the Java Code Samples blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "Understanding the concept behind ThreadLocal"

  1. Mohsin Quereshi says:

    “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.”

    Its quite possible the spawned threads from the main are not daemon. So the application does not necessarily end when the main thread’s execution is complete

Leave a Reply


seven × 3 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books