`

ThreadLocal

 
阅读更多

【汇总多个博文】

首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的。各个线程中访问的是不同的对象。 

另外,说ThreadLocal使得各线程能够保持各自独立的一个对象,并不是通过ThreadLocal.set()来实现的,而是通过每个线程中的new 对象 的操作来创建的对象,每个线程创建一个,不是什么对象的拷贝或副本。通过ThreadLocal.set()将这个新创建的对象的引用保存到各线程的自己的一个map中,每个线程都有这样一个map,执行ThreadLocal.get()时,各线程从自己的map中取出放进去的对象,因此取出来的是各自自己线程中的对象,ThreadLocal实例是作为map的key来使用的。 

如果ThreadLocal.set()进去的东西本来就是多个线程共享的同一个对象,那么多个线程的ThreadLocal.get()取得的还是这个共享对象本身,还是有并发访问问题。 

下面来看一个hibernate中典型的ThreadLocal的应用: 

Java代码   收藏代码
  1. private static final ThreadLocal threadSession = new ThreadLocal();  
  2.   
  3. public static Session getSession() throws InfrastructureException {  
  4.     Session s = (Session) threadSession.get();  
  5.     try {  
  6.         if (s == null) {  
  7.             s = getSessionFactory().openSession();  
  8.             threadSession.set(s);  
  9.         }  
  10.     } catch (HibernateException ex) {  
  11.         throw new InfrastructureException(ex);  
  12.     }  
  13.     return s;  
  14. }  


可以看到在getSession()方法中,首先判断当前线程中有没有放进去session,如果还没有,那么通过sessionFactory().openSession()来创建一个session,再将session set到线程中,实际是放到当前线程的ThreadLocalMap这个map中,这时,对于这个session的唯一引用就是当前线程中的那个ThreadLocalMap(下面会讲到),而threadSession作为这个值的key,要取得这个session可以通过threadSession.get()来得到,里面执行的操作实际是先取得当前线程中的ThreadLocalMap,然后将threadSession作为key将对应的值取出。这个session相当于线程的私有变量,而不是public的。 
显然,其他线程中是取不到这个session的,他们也只能取到自己的ThreadLocalMap中的东西。要是session是多个线程共享使用的,那还不乱套了。 
试想如果不用ThreadLocal怎么来实现呢?可能就要在action中创建session,然后把session一个个传到service和dao中,这可够麻烦的。或者可以自己定义一个静态的map,将当前thread作为key,创建的session作为值,put到map中,应该也行,这也是一般人的想法,但事实上,ThreadLocal的实现刚好相反,它是在每个线程中有一个map,而将ThreadLocal实例作为key,这样每个map中的项数很少,而且当线程销毁时相应的东西也一起销毁了,不知道除了这些还有什么其他的好处。 

总之,ThreadLocal不是用来解决对象共享访问问题的,而主要是提供了保持对象的方法和避免参数传递的方便的对象访问方式。归纳了两点: 
1。每个线程中都有一个自己的ThreadLocalMap类对象,可以将线程自己的对象保持到其中,各管各的,线程可以正确的访问到自己的对象。 
2。将一个共用的ThreadLocal静态实例作为key,将不同对象的引用保存到不同线程的ThreadLocalMap中,然后在线程执行的各处通过这个静态ThreadLocal实例的get()方法取得自己线程保存的那个对象,避免了将这个对象作为参数传递的麻烦。
 

当然如果要把本来线程共享的对象通过ThreadLocal.set()放到线程中也可以,可以实现避免参数传递的访问方式,但是要注意get()到的是那同一个共享对象,并发访问问题要靠其他手段来解决。但一般来说线程共享的对象通过设置为某类的静态变量就可以实现方便的访问了,似乎没必要放到线程中。 

ThreadLocal的应用场合,我觉得最适合的是按线程多实例(每个线程对应一个实例)的对象的访问,并且这个对象很多地方都要用到。 

下面来看看ThreadLocal的实现原理(jdk1.5源码) 

Java代码   收藏代码
  1. public class ThreadLocal<T> {  
  2.     /** 
  3.      * ThreadLocals rely on per-thread hash maps attached to each thread 
  4.      * (Thread.threadLocals and inheritableThreadLocals).  The ThreadLocal 
  5.      * objects act as keys, searched via threadLocalHashCode.  This is a 
  6.      * custom hash code (useful only within ThreadLocalMaps) that eliminates 
  7.      * collisions in the common case where consecutively constructed 
  8.      * ThreadLocals are used by the same threads, while remaining well-behaved 
  9.      * in less common cases. 
  10.      */  
  11.     private final int threadLocalHashCode = nextHashCode();  
  12.   
  13.     /** 
  14.      * The next hash code to be given out. Accessed only by like-named method. 
  15.      */  
  16.     private static int nextHashCode = 0;  
  17.   
  18.     /** 
  19.      * The difference between successively generated hash codes - turns 
  20.      * implicit sequential thread-local IDs into near-optimally spread 
  21.      * multiplicative hash values for power-of-two-sized tables. 
  22.      */  
  23.     private static final int HASH_INCREMENT = 0x61c88647;  
  24.   
  25.     /** 
  26.      * Compute the next hash code. The static synchronization used here 
  27.      * should not be a performance bottleneck. When ThreadLocals are 
  28.      * generated in different threads at a fast enough rate to regularly 
  29.      * contend on this lock, memory contention is by far a more serious 
  30.      * problem than lock contention. 
  31.      */  
  32.     private static synchronized int nextHashCode() {  
  33.         int h = nextHashCode;  
  34.         nextHashCode = h + HASH_INCREMENT;  
  35.         return h;  
  36.     }  
  37.   
  38.     /** 
  39.      * Creates a thread local variable. 
  40.      */  
  41.     public ThreadLocal() {  
  42.     }  
  43.   
  44.     /** 
  45.      * Returns the value in the current thread's copy of this thread-local 
  46.      * variable.  Creates and initializes the copy if this is the first time 
  47.      * the thread has called this method. 
  48.      * 
  49.      * @return the current thread's value of this thread-local 
  50.      */  
  51.     public T get() {  
  52.         Thread t = Thread.currentThread();  
  53.         ThreadLocalMap map = getMap(t);  
  54.         if (map != null)  
  55.             return (T)map.get(this);  
  56.   
  57.         // Maps are constructed lazily.  if the map for this thread  
  58.         // doesn't exist, create it, with this ThreadLocal and its  
  59.         // initial value as its only entry.  
  60.         T value = initialValue();  
  61.         createMap(t, value);  
  62.         return value;  
  63.     }  
  64.   
  65.     /** 
  66.      * Sets the current thread's copy of this thread-local variable 
  67.      * to the specified value.  Many applications will have no need for 
  68.      * this functionality, relying solely on the {@link #initialValue} 
  69.      * method to set the values of thread-locals. 
  70.      * 
  71.      * @param value the value to be stored in the current threads' copy of 
  72.      *        this thread-local. 
  73.      */  
  74.     public void set(T value) {  
  75.         Thread t = Thread.currentThread();  
  76.         ThreadLocalMap map = getMap(t);  
  77.         if (map != null)  
  78.             map.set(this, value);  
  79.         else  
  80.             createMap(t, value);  
  81.     }  
  82.   
  83.     /** 
  84.      * Get the map associated with a ThreadLocal. Overridden in 
  85.      * InheritableThreadLocal. 
  86.      * 
  87.      * @param  t the current thread 
  88.      * @return the map 
  89.      */  
  90.     ThreadLocalMap getMap(Thread t) {  
  91.         return t.threadLocals;  
  92.     }  
  93.   
  94.     /** 
  95.      * Create the map associated with a ThreadLocal. Overridden in 
  96.      * InheritableThreadLocal. 
  97.      * 
  98.      * @param t the current thread 
  99.      * @param firstValue value for the initial entry of the map 
  100.      * @param map the map to store. 
  101.      */  
  102.     void createMap(Thread t, T firstValue) {  
  103.         t.threadLocals = new ThreadLocalMap(this, firstValue);  
  104.     }  
  105.   
  106.     .......  
  107.   
  108.     /** 
  109.      * ThreadLocalMap is a customized hash map suitable only for 
  110.      * maintaining thread local values. No operations are exported 
  111.      * outside of the ThreadLocal class. The class is package private to 
  112.      * allow declaration of fields in class Thread.  To help deal with 
  113.      * very large and long-lived usages, the hash table entries use 
  114.      * WeakReferences for keys. However, since reference queues are not 
  115.      * used, stale entries are guaranteed to be removed only when 
  116.      * the table starts running out of space. 
  117.      */  
  118.     static class ThreadLocalMap {  
  119.   
  120.     ........  
  121.   
  122.     }  
  123.   
  124. }  



可以看到ThreadLocal类中的变量只有这3个int型: 

Java代码   收藏代码
  1. private final int threadLocalHashCode = nextHashCode();  
  2. private static int nextHashCode = 0;  
  3. private static final int HASH_INCREMENT = 0x61c88647;  


而作为ThreadLocal实例的变量只有 threadLocalHashCode 这一个,nextHashCode 和HASH_INCREMENT 是ThreadLocal类的静态变量,实际上HASH_INCREMENT是一个常量,表示了连续分配的两个ThreadLocal实例的threadLocalHashCode值的增量,而nextHashCode 的表示了即将分配的下一个ThreadLocal实例的threadLocalHashCode 的值。 

可以来看一下创建一个ThreadLocal实例即new ThreadLocal()时做了哪些操作,从上面看到构造函数ThreadLocal()里什么操作都没有,唯一的操作是这句: 

Java代码   收藏代码
  1. private final int threadLocalHashCode = nextHashCode();  


那么nextHashCode()做了什么呢: 

Java代码   收藏代码
  1. private static synchronized int nextHashCode() {  
  2.     int h = nextHashCode;  
  3.     nextHashCode = h + HASH_INCREMENT;  
  4.     return h;  
  5. }  

就是将ThreadLocal类的下一个hashCode值即nextHashCode的值赋给实例的threadLocalHashCode,然后nextHashCode的值增加HASH_INCREMENT这个值。 

因此ThreadLocal实例的变量只有这个threadLocalHashCode,而且是final的,用来区分不同的ThreadLocal实例,ThreadLocal类主要是作为工具类来使用,那么ThreadLocal.set()进去的对象是放在哪儿的呢? 

看一下上面的set()方法,两句合并一下成为 

Java代码   收藏代码
  1. ThreadLocalMap map = Thread.currentThread().threadLocals;  


这个ThreadLocalMap 类是ThreadLocal中定义的内部类,但是它的实例却用在Thread类中: 

Java代码   收藏代码
  1. public class Thread implements Runnable {  
  2.     ......  
  3.   
  4.     /* ThreadLocal values pertaining to this thread. This map is maintained 
  5.      * by the ThreadLocal class. */  
  6.     ThreadLocal.ThreadLocalMap threadLocals = null;    
  7.     ......  
  8. }  



再看这句: 

Java代码   收藏代码
  1. if (map != null)  
  2.     map.set(this, value);  


也就是将该ThreadLocal实例作为key,要保持的对象作为值,设置到当前线程的ThreadLocalMap 中,get()方法同样大家看了代码也就明白了,ThreadLocalMap 类的代码太多了,我就不帖了,自己去看源码吧。 

写了这么多,也不知讲明白了没有,有什么不当的地方还请大家指出来。

 

 

 

 

================================================================================================

 

 本文借花献佛,引用Tim Cull的博文“SimpleDateFormat: Performance Pig”介绍下ThreadLocal的简单使用,同时也对SimpleDateFormat的使用有个深入的了解。

Tim Cull 写道
Just yesterday I came across this problem “in the wild” for the third time in my career so far: an application with performance problems creating tons of java.text.SimpleDateFormat instances. So, I have to get this out there: creating a new instance of SimpleDateFormat is incredibly expensive and should be minimized. In the case that prompted this post, I was using JProfiler to profile this code that parses a CSV file and discovered that 50% of the time it took to suck in the file and make 55,000 objects out of it was spent solely in the constructor of SimpleDateFormat. It created and then threw away a new one every time it had to parse a date. Whew! 

“Great,” you think, “I’ll just create one, static instance, slap it in a field in a DateUtils helper class and life will be good.” 

Well, more precisely, life will be good about 97% of the time. A few days after you roll that code into production you’ll discover the second cool fact that’s good to know: SimpleDateFormat is not thread safe. Your code will work just fine most of the time and all of your regression tests will probably pass, but once your system gets under a production load you’ll see the occasional exception. 

“Fine,” you think, “I’ll just slap a ’synchronized’ around my use of that one, static instance.” 

Ok, fine, you could do that and you’d be more or less ok, but the problem is that you’ve now taken a very common operation (date formatting and parsing) and crammed all of your otherwise-lovely, super-parallel application through a single pipe to get it done.

 

     大致意思:Tim Cull碰到一个SimpleDateFormat带来的严重的性能问题,该问题主要有SimpleDateFormat引发,创建一个SimpleDateFormat实例的开销比较昂贵,解析字符串时间时频繁创建生命周期短暂的实例导致性能低下。即使将SimpleDateFormat定义为静态类变量,貌似能解决这个问题,但是SimpleDateFormat是非线程安全的,同样存在问题,如果用‘synchronized’线程同步同样面临问题,同步导致性能下降(线程之间序列化的获取SimpleDateFormat实例)。

    Tim Cull使用Threadlocal解决了此问题,对于每个线程SimpleDateFormat不存在影响他们之间协作的状态,为每个线程创建一个SimpleDateFormat变量的拷贝或者叫做副本,代码如下:

 

Java代码 
  1. import java.text.DateFormat;  
  2. import java.text.ParseException;  
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5. /** 
  6.  * 使用ThreadLocal以空间换时间解决SimpleDateFormat线程安全问题。 
  7.  * @author  
  8.  * 
  9.  */  
  10. public class DateUtil {  
  11.       
  12.     private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";  
  13.       
  14.     @SuppressWarnings("rawtypes")  
  15.     private static ThreadLocal threadLocal = new ThreadLocal() {  
  16.         protected synchronized Object initialValue() {  
  17.             return new SimpleDateFormat(DATE_FORMAT);  
  18.         }  
  19.     };  
  20.   
  21.     public static DateFormat getDateFormat() {  
  22.         return (DateFormat) threadLocal.get();  
  23.     }  
  24.   
  25.     public static Date parse(String textDate) throws ParseException {  
  26.         return getDateFormat().parse(textDate);  
  27.     }  
  28. }  

 

   创建一个ThreadLocal类变量,这里创建时用了一个匿名类,覆盖了initialValue方法,主要作用是创建时初始化实例。也可以采用下面方式创建;

 

Java代码 
  1. //第一次调用get将返回null  
  2. private static ThreadLocal threadLocal = new ThreadLocal();  
  3. //获取线程的变量副本,如果不覆盖initialValue,第一次get返回null,故需要初始化一个SimpleDateFormat,并set到threadLocal中  
  4. public static DateFormat getDateFormat()   
  5. {  
  6.     DateFormat df = (DateFormat) threadLocal.get();  
  7.     if(df==null){  
  8.         df = new SimpleDateFormat(DATE_FORMAT)  
  9.         threadLocal.set(df);  
  10.     }  
  11.     return df;  
  12. }  

 

   我们看下我们覆盖的initialValue方法:

 

Java代码 
  1. protected T initialValue() {  
  2.         return null;//直接返回null  
  3.     }  

 

 

 

 

 

 

==========================================================================

首先有几点需要大家清楚的:

1、  ThreadLocal只是对需要存储的对象的管理,而存储实际是由当前Thread负责。个人理解为ThreadLocal是一个操作Thread. threadLocals 的工具。

2、  使用ThreadLocal可以使对象达到线程隔离的目的。同一个ThreadLocal操作不同的Thread,实质是各个Thread对自己的变量操作。

3、  为什么要使用ThreadLocal,个人感觉有两个原因,1是与其它线程的隔离,2是可以在一个线程的生命周期中使用同一个对象,达到对象传递的作用。这样的好处是可以减少dal访问或者ws调用。

 

我这里列出一个用到ThreadLocal的例子,主要的作用是使用ThreadLocal记录用户信息以及记录用户的执行时间。这在实际应用中,可以映射为全局记录用户的权限,以及使用Threadlocal对系统的性能做一些分析等。。

 

首先有两个对象,一个是用户对象

 

Java代码  收藏代码
  1. // 简单记录用户是否可以访问,可以用于全局权限控制等  
  2. class User {  
  3.     private String name;  
  4.     private boolean isAllow;  
  5.     public User(String name, boolean isAllow) {  
  6.         this.name = name;  
  7.         this.isAllow = isAllow;  
  8.     }  
  9.     public String getName() {  
  10.         return name;  
  11.     }  
  12.     public boolean isAllow() {  
  13.         return isAllow;  
  14.     }  
  15.     @Override  
  16.     public String toString() {  
  17.         return "用户名:" + name + "\t 是否允许访问:" + isAllow;  
  18.     }  
  19. }  

 

另一个是消费时间对象

 

 

 

Java代码  收藏代码
  1. // 用于记录每一步骤耗时…,可以用于每一步的性能分析  
  2. class TimeConsumer {  
  3.     // 名称  
  4.     private String name;  
  5.     // 耗时数据列表  
  6.     private List<Long> steps;  
  7.     public TimeConsumer(String name, long start) {  
  8.         this.name = name;  
  9.         steps = new ArrayList<Long>();  
  10.         steps.add(start);  
  11.     }  
  12.     public void andStep(long step) {  
  13.         steps.add(step);  
  14.     }  
  15.     @Override  
  16.     public String toString() {  
  17.         StringBuffer br = new StringBuffer("操作[" + name + "]共有"  
  18.                 + (steps.size() - 1) + "步\n");  
  19.         for (int i = 1; i < steps.size(); i++) {  
  20.             br.append("\t|--耗时[" + (steps.get(i) - steps.get(0))  
  21.                     + "ms]\n");  
  22.         }  
  23.         br.append("\n");  
  24.         return br.toString();  
  25.     }  
  26. }  

 

 

 

接下来,建立一个对这两个对象管理的ThreadLocal的类

 

 

Java代码  收藏代码
  1. // threadlocal 管理类  
  2. class MyThreadLocal {  
  3.     // 用于全局记录user访问权限  
  4.     private ThreadLocal<User> userLocal;  
  5.     // 用于全局记录用户每一步的耗时  
  6.     private ThreadLocal<TimeConsumer> timeLocal;  
  7.     private static MyThreadLocal local = new MyThreadLocal();  
  8.     private MyThreadLocal() {  
  9.         userLocal = new ThreadLocal<User>();  
  10.         timeLocal = new ThreadLocal<TimeConsumer>();  
  11.     }  
  12.     public static MyThreadLocal getInstanse() {  
  13.         return local;  
  14.     }  
  15.     public void addUser(User user) {  
  16.         userLocal.set(user);  
  17.     }  
  18.     public User getUser() {  
  19.         return userLocal.get();  
  20.     }  
  21.     public void addTime(TimeConsumer timeConsumer) {  
  22.         timeLocal.set(timeConsumer);  
  23.     }  
  24.     public void addTime(long l) {  
  25.         TimeConsumer time = timeLocal.get();  
  26.         timeLocal.remove();  
  27.         time.andStep(l);  
  28.         timeLocal.set(time);  
  29.     }  
  30.     public TimeConsumer getTime() {  
  31.         return timeLocal.get();  
  32.     }  
  33. }  

 

 

 

 

接下来就可以对Threadlocal进行测试了。为了模拟多线程,我这里自己实现了多线程

 

 

Java代码  收藏代码
  1. public class CoreThreadLocal {  
  2.     public static void main(String[] args) {  
  3.         new Thread(new TestRunnable("name1", 1000L, true)).start();  
  4.         new Thread(new TestRunnable("name2", 700L, true)).start();  
  5.         new Thread(new TestRunnable("name3"888false)).start();  
  6.     }  
  7. }  
  8.   
  9. // 用于测试,多线程实现  
  10. class TestRunnable implements Runnable {  
  11.     String name;  
  12.     long l;  
  13.     boolean isAllow;  
  14.   TestRunnable(String name, long l, boolean isAllow) {  
  15.         this.name = name;  
  16.         this.l = l;  
  17.         this.isAllow = isAllow;  
  18.     }  
  19.     public void run() {  
  20.         MyThreadLocal local = MyThreadLocal.getInstanse();  
  21.         local.addUser(new User(name, isAllow));  
  22.         local.addTime(new TimeConsumer(name, System.currentTimeMillis()));  
  23.         // 做某个业务,并记录时间  
  24.         doThings(l);  
  25.         local.addTime(System.currentTimeMillis());  
  26.         // 做某个业务,并记录时间  
  27.         doThings(l);  
  28.         local.addTime(System.currentTimeMillis());  
  29.         // 业务做完,打印日志  
  30.         System.out.println(local.getUser());  
  31.         System.out.println(local.getTime());  
  32.     }  
  33.     // 模拟具体业务的处理步骤  
  34.     private void doThings(long l) {  
  35.         try {  
  36.             Thread.sleep(l);  
  37.         } catch (InterruptedException e) {  
  38.             e.printStackTrace();  
  39.         }  
  40.     }  
  41. }  

 

 

 

 

运行上面的程序得到结果如下:

 

 

 

Java代码  收藏代码
  1. 用户名:name2    是否允许访问:true  
  2. 操作[name2]共有2步  
  3.     |--耗时[703ms]  
  4.     |--耗时[1406ms]  
  5.   
  6.   
  7. 用户名:name3    是否允许访问:false  
  8. 操作[name3]共有2步  
  9.     |--耗时[891ms]  
  10.     |--耗时[1781ms]  
  11.   
  12.   
  13. 用户名:name1    是否允许访问:true  
  14. 操作[name1]共有2步  
  15.     |--耗时[1000ms]  
  16.     |--耗时[2000ms]  

 

 

 

 

通过上面的测试程序,可以大概了解ThreadLocal的使用方法以及作用。

如果要深入使用,建议还是看下源码吧…

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics