Java中的ThreadLocal

来源:互联网 发布:淘宝摄影布光 编辑:程序博客网 时间:2024/06/05 00:18
这一篇之所以讲ThreadLocal,是因为之前在读Handler,Looper的源码过程(见http://maosidiaoxian.iteye.com/blog/1927735)中,看到了这个类,引起了我的兴趣。而后来发现JAVA1.6中的TheadLocal类,和我在android源码看到的这个ThreadLocal类代码是不一样的。所以这篇先讲一下Java的ThreadLocal。 
Java中ThreadLocal在Java1.2就已经提出了,后来重构过,所以我在想android中的这个类的实现是不是重构过之前的版本优化过的,由于未找到早前版本该类的代码,所以只能进行猜测。 

ThreadLocal用于提供线程局部变量,即通过这里的get()和set()方法访问某个变量的线程都有自己的局部变量。但在这里需要注意的是,它是通过各个线程自己创建对象然后调用这里的set方法设置进去,而不是由ThreadLocal自己来创建变量的副本的。就像上面链接的那一篇文章里面提到的android的Looper类所用的(虽然Android里ThreadLocal实现代码不一样,但用法是一样的),代码如下: 
Java代码  收藏代码
  1. static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();  
  2. private static void prepare(boolean quitAllowed) {  
  3.     if (sThreadLocal.get() != null) {  
  4.         throw new RuntimeException("Only one Looper may be created per thread");  
  5.     }  
  6.     sThreadLocal.set(new Looper(quitAllowed));  
  7. }  

可以看到,线程中的局部变量,是在线程中创建,然后调用ThreadLocal.set()方法设置进去的。 

下面详细读一下ThreadLocal这个类,看看它是怎么实现的(jdk1.6的源码)。 

 
从上图可以看到ThreadLocal有三个变(常)量,代码如下: 
Java代码  收藏代码
  1. /** 
  2.  * ThreadLocals rely on per-thread linear-probe hash maps attached 
  3.  * to each thread (Thread.threadLocals and 
  4.  * inheritableThreadLocals).  The ThreadLocal objects act as keys, 
  5.  * searched via threadLocalHashCode.  This is a custom hash code 
  6.  * (useful only within ThreadLocalMaps) that eliminates collisions 
  7.  * in the common case where consecutively constructed ThreadLocals 
  8.  * are used by the same threads, while remaining well-behaved in 
  9.  * less common cases. 
  10.  */  
  11. private final int threadLocalHashCode = nextHashCode();  
  12.   
  13. /** 
  14.  * The next hash code to be given out. Updated atomically. Starts at 
  15.  * zero. 
  16.  */  
  17. private static AtomicInteger nextHashCode =  
  18.     new AtomicInteger();  
  19.   
  20. /** 
  21.  * The difference between successively generated hash codes - turns 
  22.  * implicit sequential thread-local IDs into near-optimally spread 
  23.  * multiplicative hash values for power-of-two-sized tables. 
  24.  */  
  25. private static final int HASH_INCREMENT = 0x61c88647;  

其中HASH_INCREMENT 是一个常量,它表示连续的两个ThreadLocal实例的threadLocalHashCode值的增量。至于为什么用0x61c88647常量,我也没明白,只百度出一堆跟加密算法有关的内容。nextHashCode变量是AtomicInteger类型,AtomicInteger是一个提供原子操作的Integer类,简单而言就是不用Synchronized关键字也可以进行线程安全的加减操作。 

当创建一个ThreadLocal对象时,会进行以下操作: 
Java代码  收藏代码
  1. public ThreadLocal() {  
  2. }  
  3.   
  4. private final int threadLocalHashCode = nextHashCode();  

我们再来看nextHashCode()这个方法,代码如下: 
Java代码  收藏代码
  1. /** 
  2.  * Returns the next hash code. 
  3.  */  
  4. private static int nextHashCode() {  
  5.     return nextHashCode.getAndAdd(HASH_INCREMENT);  
  6. }  

它是返回一个hash code,同时对nextHashCode加上增量HASH_INCREMENT。也就是在初始化ThreadLocal的实例过程中,做的仅仅是将一个哈希值赋给实例的threadLocalHashCode,并生成下一个哈希值。而前面可以看到threadLocalHashCode是final的,在个类中,它用来区分不同的ThreadLocal对象。 

在前面的图当中,我们可以看到在ThreadLocal里还有一个ThreadLocalMap的内部类,从类名来看应该是被设计来保存线程局部变量的Map,但是在ThreadLocal类或它的实例当中,并没有其他变量,那么通过ThreadLocal.set()放进去的值又是怎么保存的呢? 
我们继续看ThreadLocal的set()和其他方法: 
Java代码  收藏代码
  1. /** 
  2.  * Sets the current thread's copy of this thread-local variable 
  3.  * to the specified value.  Most subclasses will have no need to 
  4.  * override this method, relying solely on the {@link #initialValue} 
  5.  * method to set the values of thread-locals. 
  6.  * 
  7.  * @param value the value to be stored in the current thread's copy of 
  8.  *        this thread-local. 
  9.  */  
  10. public void set(T value) {  
  11.     Thread t = Thread.currentThread();  
  12.     ThreadLocalMap map = getMap(t);  
  13.     if (map != null)  
  14.         map.set(this, value);  
  15.     else  
  16.         createMap(t, value);  
  17. }  
  18.   
  19. /** 
  20.  * Get the map associated with a ThreadLocal. Overridden in 
  21.  * InheritableThreadLocal. 
  22.  * 
  23.  * @param  t the current thread 
  24.  * @return the map 
  25.  */  
  26. ThreadLocalMap getMap(Thread t) {  
  27.     return t.threadLocals;  
  28. }  
  29.   
  30. /** 
  31.  * Create the map associated with a ThreadLocal. Overridden in 
  32.  * InheritableThreadLocal. 
  33.  * 
  34.  * @param t the current thread 
  35.  * @param firstValue value for the initial entry of the map 
  36.  * @param map the map to store. 
  37.  */  
  38. void createMap(Thread t, T firstValue) {  
  39.     t.threadLocals = new ThreadLocalMap(this, firstValue);  
  40. }  

从上面的代码可以看到,set()方法是调用ThreadLocalMap.set()方法保存到ThreadLocalMap实例当中,但是ThreadLocalMap实例却不是保存在Thread中,它通过getMap()方法去取,当取不到的时候就去创建,但是创建之后却是保存在Thread实例中。可以看到Thread.java的代码有如下声明: 
Java代码  收藏代码
  1. ThreadLocal.ThreadLocalMap threadLocals = null;  

这种设计很巧妙,线程中有各自的map,而把ThreadLocal实例作为key,这样除了当线程销毁时相关的线程局部变量被销毁之外,还让性能提升了很多。 

看完set()方法,再来看get()方法,它的代码如下: 
Java代码  收藏代码
  1. /** 
  2.  * Returns the value in the current thread's copy of this 
  3.  * thread-local variable.  If the variable has no value for the 
  4.  * current thread, it is first initialized to the value returned 
  5.  * by an invocation of the {@link #initialValue} method. 
  6.  * 
  7.  * @return the current thread's value of this thread-local 
  8.  */  
  9. public T get() {  
  10.     Thread t = Thread.currentThread();  
  11.     ThreadLocalMap map = getMap(t);  
  12.     if (map != null) {  
  13.         ThreadLocalMap.Entry e = map.getEntry(this);  
  14.         if (e != null)  
  15.             return (T)e.value;  
  16.     }  
  17.     return setInitialValue();  
  18. }  
  19.   
  20. /** 
  21.  * Variant of set() to establish initialValue. Used instead 
  22.  * of set() in case user has overridden the set() method. 
  23.  * 
  24.  * @return the initial value 
  25.  */  
  26. private T setInitialValue() {  
  27.     T value = initialValue();  
  28.     Thread t = Thread.currentThread();  
  29.     ThreadLocalMap map = getMap(t);  
  30.     if (map != null)  
  31.         map.set(this, value);  
  32.     else  
  33.         createMap(t, value);  
  34.     return value;  
  35. }  
  36.   
  37. /** 
  38.  * Returns the current thread's "initial value" for this 
  39.  * thread-local variable.  This method will be invoked the first 
  40.  * time a thread accesses the variable with the {@link #get} 
  41.  * method, unless the thread previously invoked the {@link #set} 
  42.  * method, in which case the <tt>initialValue</tt> method will not 
  43.  * be invoked for the thread.  Normally, this method is invoked at 
  44.  * most once per thread, but it may be invoked again in case of 
  45.  * subsequent invocations of {@link #remove} followed by {@link #get}. 
  46.  * 
  47.  * <p>This implementation simply returns <tt>null</tt>; if the 
  48.  * programmer desires thread-local variables to have an initial 
  49.  * value other than <tt>null</tt>, <tt>ThreadLocal</tt> must be 
  50.  * subclassed, and this method overridden.  Typically, an 
  51.  * anonymous inner class will be used. 
  52.  * 
  53.  * @return the initial value for this thread-local 
  54.  */  
  55. protected T initialValue() {  
  56.     return null;  
  57. }  

可以看到在get()方法中,是通过当前线程获取map,再从map当中取得对象。如果取不到(如map为null或取到的值为null),则调用setInitialValue()方法对其设置初始值。setInitialValue()方法会调用initialValue()方法得到一个初始值(默认为null),然后当Thread中的map不为空时,把初始值设置进去,否则为它创建一个ThreadLocalMap对象(但不会调用map的set方法保存这个初始值),最后返回这个初始值。 

最后看remove()方法,它提供了移除此线程局部变量在当前进程的值。代码如下:
Java代码  收藏代码
  1. /** 
  2.  * Removes the current thread's value for this thread-local 
  3.  * variable.  If this thread-local variable is subsequently 
  4.  * {@linkplain #get read} by the current thread, its value will be 
  5.  * reinitialized by invoking its {@link #initialValue} method, 
  6.  * unless its value is {@linkplain #set set} by the current thread 
  7.  * in the interim.  This may result in multiple invocations of the 
  8.  * <tt>initialValue</tt> method in the current thread. 
  9.  * 
  10.  * @since 1.5 
  11.  */  
  12.  public void remove() {  
  13.      ThreadLocalMap m = getMap(Thread.currentThread());  
  14.      if (m != null)  
  15.          m.remove(this);  
  16.  }  


关于ThreadLocal就读到这里,有时间再写下它的内部类ThreadLocalMap。 
参考文章: 
lujh99. 正确理解ThreadLocal. http://www.iteye.com/topic/103804
原创粉丝点击