现在的位置: 首页 > 综合 > 正文

Threadlocal源码分析

2018年01月26日 ⁄ 综合 ⁄ 共 5112字 ⁄ 字号 评论关闭

综述:每个thread有个threadlocalmap对象 ,这个map对象用来存储此thread中的所有的threadlocal对象,每个threadlocal对象包含一个独一无二的threadlocalhashcode值

1.关联类

ThreadLocal: 线程局部变量

Thread:线程对象



2. Thread与ThreadLocal如何关联?

 ThreadLocal类:

 

Java代码  收藏代码
  1.   /** 
  2.     * Variant of set() to establish initialValue. Used instead 
  3.     * of set() in case user has overridden the set() method. 
  4.     * 
  5.     * @return the initial value 
  6.     */  
  7.    private T setInitialValue() {  
  8.        T value = initialValue();  
  9.        Thread t = Thread.currentThread();  
  10.        ThreadLocalMap map = getMap(t);  
  11.        if (map != null)  
  12.            map.set(this, value);  
  13.        else  
  14.            createMap(t, value);  
  15.        return value;  
  16.    }  
  17.   
  18. /** 
  19.     * Create the map associated with a ThreadLocal. Overridden in 
  20.     * InheritableThreadLocal. 
  21.     * 
  22.     * @param t the current thread 
  23.     * @param firstValue value for the initial entry of the map 
  24.     * @param map the map to store. 
  25.     */  
  26.    void createMap(Thread t, T firstValue) {  
  27.        t.threadLocals = new ThreadLocalMap(this, firstValue);  
  28.    }  

 

 

 

 Thread类:

Java代码  收藏代码
  1. /* ThreadLocal values pertaining to this thread. This map is maintained 
  2.     * by the ThreadLocal class. */  
  3.    ThreadLocal.ThreadLocalMap threadLocals = null;  

 

 

在每一个线程中都声明了一个成员变量ThreadLocalMap,而它的创建则是在ThreadLocal中通过createMap实现。第一次直接通过构造方法保存对象,之后取得ThreadLocalMap的引用进行set,保存在entry中。



3.一个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.      * Sets the current thread's copy of this thread-local variable 
  15.      * to the specified value.  Most subclasses will have no need to  
  16.      * override this method, relying solely on the {@link #initialValue} 
  17.      * method to set the values of thread-locals. 
  18.      * 
  19.      * @param value the value to be stored in the current thread's copy of 
  20.      *        this thread-local. 
  21.      */  
  22.     public void set(T value) {  
  23.         Thread t = Thread.currentThread();  
  24.         ThreadLocalMap map = getMap(t);  
  25.         if (map != null)  
  26.             map.set(this, value);  
  27.         else  
  28.             createMap(t, value);  
  29.     }  

 

 

threadLocalHashCode是ThreadLocal的唯一标识,ThreadLocalMap将ThreadLocal做为key值,因此同一个ThreadLocal对应的value将有且仅有一个,并只保存最后一次value值。起初脑袋被门夹了,一直想不明白ThreadLocal无论你set多少次只保存最后一个对象,定义ThreadLocalMap仅仅用来保存一个对象?后来才发现,原来是钻牛角尖了,当前线程下多new 几个ThreadLocal不就行了(学艺不精,思维没打开啊)。



4.ThreadLocalMap中Entry继承了WeakReference

虽然实现了弱引用,在内存不够的时候,即使还被引用,也能被GC回收,但是最好习惯性手动调用下

Java代码  收藏代码
  1.     /** 
  2.       * Remove the entry for key. 
  3.       */  
  4.      private void remove(ThreadLocal key) {  
  5.          Entry[] tab = table;  
  6.          int len = tab.length;  
  7.          int i = key.threadLocalHashCode & (len-1);  
  8.          for (Entry e = tab[i];  
  9. e != null;  
  10. e = tab[i = nextIndex(i, len)]) {  
  11.              if (e.get() == key) {  
  12.                  e.clear();  
  13.                  expungeStaleEntry(i);  
  14.                  return;  
  15.              }  
  16.          }  
  17.      }  

 

 

如果你所应用的环境中存在线程池,当前线程没被销毁。下个应用可能使用上个线程,可能会造成上个线程的数据显示在下个线程中。所以在结束使用ThreadLocal时,记得手动调用下remove


5.ThreadLocalMap保存算法

Java代码  收藏代码
  1. /** 
  2.          * Set the value associated with key. 
  3.          * 
  4.          * @param key the thread local object 
  5.          * @param value the value to be set 
  6.          */  
  7.         private void set(ThreadLocal key, Object value) {  
  8.   
  9.             // We don't use a fast path as with get() because it is at  
  10.             // least as common to use set() to create new entries as  
  11.             // it is to replace existing ones, in which case, a fast  
  12.             // path would fail more often than not.  
  13.   
  14.             Entry[] tab = table;  
  15.             int len = tab.length;  
  16.             int i = key.threadLocalHashCode & (len-1);  
  17.   
  18.             for (Entry e = tab[i];  
  19.          e != null;  
  20.          e = tab[i = nextIndex(i, len)]) {  
  21.                 ThreadLocal k = e.get();  
  22.   
  23.                 if (k == key) {  
  24.                     e.value = value;  
  25.                     return;  
  26.                 }  
  27.   
  28.                 if (k == null) {  
  29.                     replaceStaleEntry(key, value, i);  
  30.                     return;  
  31.                 }  
  32.             }  
  33.   
  34.             tab[i] = new Entry(key, value);  
  35.             int sz = ++size;  
  36.             if (!cleanSomeSlots(i, sz) && sz >= threshold)  
  37.                 rehash();  
  38.         }  

 拿ThreadLocal的threadLocalHashCode与长度减一相与,求出哈希表的位置。如果这个插槽已有不为空的entry,则依次遍历之后的位置,当达到最大长度时,重新从第一个位置开始找,直到找着为null的插槽.增加size记录已有多少个元素,在查找过程中会判断这个entry弱引用是否已被回收,如果已回收则清楚value重新释放这个插糟并size-1,如果size等于加载因子则按2倍扩容。

 

 

6.总结

通过Thread.currentThread()取得当前线程,在这个线程中活动期间创建多个ThreadLocal放入当前线程的ThreadLocalMap中,相当于将多线程分开,每个人操作自己的线程,在自己线程中创建与使用自己的变量,各管各的,这就是所谓的“为每一个使用该变量的线程都提供一个变量值的副本,使每一个线程都可以独立地改变自己的副本”。

与synchronized相比只了解了其中之一的优点:“以空间换时间”。

ThreadLocal会随着线程的销毁而销毁

抱歉!评论已关闭.