Tuesday, November 2, 2010

Why Use ThreadLocal Variable in Java

java.lang.ThreadLocal  class can be used when you want that each thread should have it's own copy of values in a shared object and in multithreaded environment.

Example:

import java.util.HashMap;
import java.util.Map;


public class Test
{
    private static Map<String, String>  map  = new HashMap<String, String>();
    private static ThreadLocal<Map<String, String>> tmap = new  

                       ThreadLocal<Map<String, String>>()
    {
       protected java.util.Map<String, String> initialValue()
      {
         return new HashMap<String, String>();
      }
    };

 private static int cnt = 1;
 public static void main(String[] st)
   throws Exception
 {
     new ThreadRun().start();
     Thread.sleep(1000);
     System.out.println("**************************************");
     cnt++;
     new ThreadRun().start();
 }

 private static class ThreadRun
  extends Thread
 {
  @Override
  public void run()
  {
          tmap.get().put("One" + cnt, "ThreadLocal" + cnt);
          map.put("One" + cnt, "OneValue" + cnt);
          System.out.println(cnt + "....ThreadLocal=" + tmap.get());
          System.out.println(cnt + "....RunOne=" + map);
  }
 }
}


Analysis of Example: Above example is having three shared variables(they are static) one is map (type of HashMap) and other is tmap(type of ThreadLocal) and intger counter cnt.
One static class ThreadRun which will process the shared objects map and tmap. When we run this program get the following result.

1....ThreadLocal={One1=ThreadLocal1}
1....RunOne={One1=OneValue1}
**************************************
2....ThreadLocal={One2=ThreadLocal2}
2....RunOne={One2=OneValue2, One1=OneValue1}

When we ran the first thread it put values in map and tmap. But when second thread runs values are being put in map object whereas values in tmap is being put in different HashMap so for map same HashMap is used for all thread but if we use ThreadLocal then there will be separate HahMap objects for separate threads because when a new thread tries to get the values from ThreadLocal variable it's initialValues method is called which returns new HashMap for each new thread, so tmap is having only one value whereas map is having two values.

initialValue method of ThreadLocal provides the initial value for a Thread. If the accessing Thread is not having any associated Map then a new HahMap will be returned otherwise stored HashMap will be returned.

Use: One use for this is to distribute JDBC Connection objects to different request Threads because JDBC Connections should not be shared among different request processing.

No comments:

Post a Comment