【Java并发编程实践】— ThreadLocal分析

来源:互联网 发布:小米2s支持4g网络吗 编辑:程序博客网 时间:2024/04/29 16:18

前言

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


ThreadLocal的作用

1.提供了保存对象的方法:每个线程中都有一个自己的ThreadLocalMap类对象,可以将线程自己的对象保持到其中,各管各的,线程可以正确的访问到自己的对象。

2.避免参数传递的方便的对象访问方式:将一个共用的ThreadLocal静态实例作为key,将不同对象的引用保存到不同线程的ThreadLocalMap中,然后在线程执行的各处通过这个静态ThreadLocal实例的get()方法取得自己线程保存的那个对象,避免了将这个对象作为参数传递的麻烦。


理解ThreadLocal中提到的变量副本

“当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本” —— 并不是通过ThreadLocal.set( )实现的,而是每个线程使用“new对象”(或拷贝) 的操作来创建对象副本, 通过ThreadLocal.set()将这个新创建的对象的引用保存到各线程的自己的一个map中,每个线程都有这样一个map,执行ThreadLocal.get()时,各线程从自己的map中取出放进去的对象,因此取出来的是各自自己线程中的对象(ThreadLocal实例是作为map的key来使用的)。


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

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * 如果ThreadLocal.set()进去的是一个多线程共享对象,那么Thread.get()获取的还是这个共享对象本身—————并不是该共享对象的副本。 
  3.  * 假如:其中其中一个线程对这个共享对象内容作了修改,那么将会反映到其它线程获取的共享对象中————所以说 ThreadLocal还是有并发访问问题的! 
  4.  */  
  5. public class Test implements Runnable  
  6. {  
  7.     private ThreadLocal<Person> threadLocal = new ThreadLocal<Person>();  
  8.       
  9.     private Person person;  
  10.       
  11.     public Test(Person person)  
  12.     {  
  13.         this.person = person;  
  14.     }  
  15.       
  16.     public static void main(String[] args) throws InterruptedException  
  17.     {  
  18.         //多线程共享的对象  
  19.         Person sharePerson = new Person(110,"Sone");  
  20.         Test test = new Test(sharePerson);  
  21.           
  22.         System.out.println("sharePerson原始内容:"+sharePerson);  
  23.           
  24.         Thread th = new Thread(test);  
  25.         th.start();  
  26.         th.join();  
  27.           
  28.         //通过ThreadLocal获取对象  
  29.         Person localPerson = test.getPerson();  
  30.           
  31.         System.out.println("判断localPerson与sharePerson的引用是否一致:"+(localPerson==localPerson));  
  32.         System.out.println("sharePerson被改动之后的内容:"+sharePerson);  
  33.     }  
  34.       
  35.     @Override  
  36.     public void run()  
  37.     {  
  38.         String threadName = Thread.currentThread().getName();  
  39.         System.out.println(threadName+":Get a copy of the variable and change!!!");  
  40.         Person p = getPerson();  
  41.         p.setId(741741);  
  42.         p.setName("Boy");  
  43.     }  
  44.       
  45.     public Person getPerson(){  
  46.         Person p = (Person)threadLocal.get();  
  47.         if (p==null)  
  48.         {  
  49.             p= this.person;  
  50.             //set():进去的是多线程共享的对象  
  51.             threadLocal.set(p);  
  52.         }  
  53.         return p;  
  54.     }  
  55.   
  56. }  

理解Thread和 ThreadLocal对变量的引用关系

实际上Thread和ThreadLocal对变量引用关系就像是坐标系中的X轴和Y轴,是从两个维度上来组织对变量的引用的。  

1.首先说Thread:

我们知道一个ThreadOne的执行会贯穿多个方法MethodA、MethodB、MethodC这些方法可能分布于不同的类实例。假设,这些方法分别使用了ThreadLocalA、ThreadLocalB、ThreadLocalC来保存线程本地变量,那么这些变量都存于ThreadOne的Map中,并使用各自的ThreadLocal实例作为key。 因此,可以认为,借助ThreanLocal的set方法,在X轴上,Thread横向关联同一线程上下文中来自多个Method的变量引用副本。 

2.接着说ThreadLocal:

一个MethodA中的X变量将被多个线程ThreadOne、ThreadTwo、ThreadThree所访问。假设MethodA使用ThreadLocal存储X,通过set方法,以ThreadLocal作为key值,将不同线程来访时的不同的变量值引用保存于ThreadOne、ThreadTwo、ThreadThree的各自线程上下文中,确保每个线程有自己的一个变量值。因此,可以认为,ThreadLocal是以Method为Y轴,纵向关联了处于同一方法中的不同线程上的变量。


ThreadLocal的应用

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

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  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作为这个值(session)的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.set()放到线程中也可以,可以实现避免参数传递的访问方式,但是要注意get()到的是那同一个共享对象,并发访问问题要靠其他手段来解决。但一般来说线程共享的对象通过设置为某类的静态变量就可以实现方便的访问了,似乎没必要放到线程中。


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


ThreadLocal源码分析

下面来看看ThreadLocal的实现原理(JDK1.6源码)

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. public class ThreadLocal<T> {  
  2.     /** 
  3.      * ThreadLocals rely on per-thread linear-probe hash maps attached 
  4.      * to each thread (Thread.threadLocals and 
  5.      * inheritableThreadLocals).  The ThreadLocal objects act as keys, 
  6.      * searched via threadLocalHashCode.  This is a custom hash code 
  7.      * (useful only within ThreadLocalMaps) that eliminates collisions 
  8.      * in the common case where consecutively constructed ThreadLocals 
  9.      * are used by the same threads, while remaining well-behaved in 
  10.      * less common cases. 
  11.      */  
  12.     private final int threadLocalHashCode = nextHashCode();  
  13.   
  14.     /** 
  15.      * The next hash code to be given out. Updated atomically. Starts at 
  16.      * zero. 
  17.      */  
  18.     private static AtomicInteger nextHashCode =   
  19.     new AtomicInteger();  
  20.   
  21.     /** 
  22.      * The difference between successively generated hash codes - turns 
  23.      * implicit sequential thread-local IDs into near-optimally spread 
  24.      * multiplicative hash values for power-of-two-sized tables. 
  25.      */  
  26.     private static final int HASH_INCREMENT = 0x61c88647;  
  27.   
  28.     /** 
  29.      * Returns the next hash code. 
  30.      */  
  31.     private static int nextHashCode() {  
  32.     return nextHashCode.getAndAdd(HASH_INCREMENT);   
  33.     }  
  34.   
  35.     /** 
  36.      * Returns the current thread's "initial value" for this 
  37.      * thread-local variable.  This method will be invoked the first 
  38.      * time a thread accesses the variable with the {@link #get} 
  39.      * method, unless the thread previously invoked the {@link #set} 
  40.      * method, in which case the <tt>initialValue</tt> method will not 
  41.      * be invoked for the thread.  Normally, this method is invoked at 
  42.      * most once per thread, but it may be invoked again in case of 
  43.      * subsequent invocations of {@link #remove} followed by {@link #get}. 
  44.      * 
  45.      * <p>This implementation simply returns <tt>null</tt>; if the 
  46.      * programmer desires thread-local variables to have an initial 
  47.      * value other than <tt>null</tt>, <tt>ThreadLocal</tt> must be 
  48.      * subclassed, and this method overridden.  Typically, an 
  49.      * anonymous inner class will be used. 
  50.      * 
  51.      * @return the initial value for this thread-local 
  52.      */  
  53.     protected T initialValue() {  
  54.         return null;  
  55.     }  
  56.   
  57.     /** 
  58.      * Creates a thread local variable. 
  59.      */  
  60.     public ThreadLocal() {  
  61.     }  
  62.   
  63.     /** 
  64.      * Returns the value in the current thread's copy of this 
  65.      * thread-local variable.  If the variable has no value for the 
  66.      * current thread, it is first initialized to the value returned 
  67.      * by an invocation of the {@link #initialValue} method. 
  68.      * 
  69.      * @return the current thread's value of this thread-local 
  70.      */  
  71.     public T get() {  
  72.         Thread t = Thread.currentThread();  
  73.         ThreadLocalMap map = getMap(t);  
  74.         if (map != null) {  
  75.             ThreadLocalMap.Entry e = map.getEntry(this);  
  76.             if (e != null)  
  77.                 return (T)e.value;  
  78.         }  
  79.         return setInitialValue();  
  80.     }  
  81.   
  82.     /** 
  83.      * Variant of set() to establish initialValue. Used instead 
  84.      * of set() in case user has overridden the set() method. 
  85.      * 
  86.      * @return the initial value 
  87.      */  
  88.     private T setInitialValue() {  
  89.         T value = initialValue();  
  90.         Thread t = Thread.currentThread();  
  91.         ThreadLocalMap map = getMap(t);  
  92.         if (map != null)  
  93.             map.set(this, value);  
  94.         else  
  95.             createMap(t, value);  
  96.         return value;  
  97.     }  
  98.   
  99.     /** 
  100.      * Sets the current thread's copy of this thread-local variable 
  101.      * to the specified value.  Most subclasses will have no need to  
  102.      * override this method, relying solely on the {@link #initialValue} 
  103.      * method to set the values of thread-locals. 
  104.      * 
  105.      * @param value the value to be stored in the current thread's copy of 
  106.      *        this thread-local. 
  107.      */  
  108.     public void set(T value) {  
  109.         Thread t = Thread.currentThread();  
  110.         ThreadLocalMap map = getMap(t);  
  111.         if (map != null)  
  112.             map.set(this, value);  
  113.         else  
  114.             createMap(t, value);  
  115.     }  
  116.   
  117.     /** 
  118.      * Removes the current thread's value for this thread-local 
  119.      * variable.  If this thread-local variable is subsequently 
  120.      * {@linkplain #get read} by the current thread, its value will be 
  121.      * reinitialized by invoking its {@link #initialValue} method, 
  122.      * unless its value is {@linkplain #set set} by the current thread 
  123.      * in the interim.  This may result in multiple invocations of the 
  124.      * <tt>initialValue</tt> method in the current thread. 
  125.      * 
  126.      * @since 1.5 
  127.      */  
  128.      public void remove() {  
  129.          ThreadLocalMap m = getMap(Thread.currentThread());  
  130.          if (m != null)  
  131.              m.remove(this);  
  132.      }  
  133.   
  134.     /** 
  135.      * Get the map associated with a ThreadLocal. Overridden in 
  136.      * InheritableThreadLocal. 
  137.      * 
  138.      * @param  t the current thread 
  139.      * @return the map 
  140.      */  
  141.     ThreadLocalMap getMap(Thread t) {  
  142.         return t.threadLocals;  
  143.     }  
  144.   
  145.     /** 
  146.      * Create the map associated with a ThreadLocal. Overridden in 
  147.      * InheritableThreadLocal. 
  148.      * 
  149.      * @param t the current thread 
  150.      * @param firstValue value for the initial entry of the map 
  151.      * @param map the map to store. 
  152.      */  
  153.     void createMap(Thread t, T firstValue) {  
  154.         t.threadLocals = new ThreadLocalMap(this, firstValue);  
  155.     }  
  156.   
  157.     /** 
  158.      * Factory method to create map of inherited thread locals. 
  159.      * Designed to be called only from Thread constructor. 
  160.      * 
  161.      * @param  parentMap the map associated with parent thread 
  162.      * @return a map containing the parent's inheritable bindings 
  163.      */  
  164.     static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {  
  165.         return new ThreadLocalMap(parentMap);  
  166.     }  
  167.   
  168.     /** 
  169.      * Method childValue is visibly defined in subclass 
  170.      * InheritableThreadLocal, but is internally defined here for the 
  171.      * sake of providing createInheritedMap factory method without 
  172.      * needing to subclass the map class in InheritableThreadLocal. 
  173.      * This technique is preferable to the alternative of embedding 
  174.      * instanceof tests in methods. 
  175.      */  
  176.     T childValue(T parentValue) {  
  177.         throw new UnsupportedOperationException();  
  178.     }  
  179.     static class ThreadLocalMap {  
  180.     ......  
  181.     }  
  182. }  

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

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. private final int threadLocalHashCode = nextHashCode();  
  2. private static AtomicInteger nextHashCode =   
  3.     new AtomicInteger();  
  4. 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] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. private final int threadLocalHashCode = nextHashCode();  
那么nextHashCode()做了什么呢:
[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. private static int nextHashCode() {  
  2.     return nextHashCode.getAndAdd(HASH_INCREMENT);   
  3. }  
就是将ThreadLocal类的下一个hashCode值即nextHashCode的值赋给实例的threadLocalHashCode


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

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

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. ThreadLocalMap map = Thread.currentThread().threadLocals;  
这个ThreadLocalMap 类是ThreadLocal中定义的内部类,但是它的实例却用在Thread类中:
[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  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] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. if (map != null)    
  2.     map.set(this, value);    

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

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


转载地址:http://www.iteye.com/topic/103804

0 0
原创粉丝点击