zoukankan      html  css  js  c++  java
  • ThreadLocal源码分析:(一)set(T value)方法

    在ThreadLocal的get(),set()的时候都会清除线程ThreadLocalMap里所有key为null的value。 
    而ThreadLocal的remove()方法会先将Entry中对key的弱引用断开,设置为null,然后再清除对应的key为null的value。 
    本文分析set方法

    系列文章链接:

    http://www.cnblogs.com/noodleprince/p/8657399.html

    http://www.cnblogs.com/noodleprince/p/8658333.html

    http://www.cnblogs.com/noodleprince/p/8659028.html

    ThreadLocal类的set方法

    1 public void set(T value) {
    2     Thread t = Thread.currentThread();
    3     ThreadLocalMap map = getMap(t);     // 获取线程t中的ThreadLocalMap
    4     if (map != null)
    5         map.set(this, value);   // 见代码1
    6     else
    7         createMap(t, value);    // 创建新的ThreadLocalMap
    8 }

    可以看到,set()方法中就是map.set()方法是在干实事,深入进去看看。

    代码1: 
    ThreadLocal.ThreadLocalMap类的set方法

     1 private void set(ThreadLocal<?> key, Object value) {
     2     Entry[] tab = table;
     3     int len = tab.length;
     4     int i = key.threadLocalHashCode & (len-1);
     5 
     6     for (Entry e = tab[i];
     7          e != null;
     8          e = tab[i = nextIndex(i, len)]) {
     9         ThreadLocal<?> k = e.get(); // 通过value来反查key,比较少见的操作,见代码2
    10 
    11         if (k == key) { // 在ThreadLocalMap对象中找到了要设置的key,则直接覆盖原来的value
    12             e.value = value;
    13             return;
    14         }
    15 
    16         if (k == null) {
    17             replaceStaleEntry(key, value, i);   // 见代码8
    18             return;
    19         }
    20     }
    21 
    22     tab[i] = new Entry(key, value);     // 新增一个Entry节点
    23     int sz = ++size;
    24     if (!cleanSomeSlots(i, sz) && sz >= threshold)      // 如果size大于等于threshold,且执行cleanSomeSlots方法(见代码3)返回为false
    25         rehash();   // 执行rehash方法,见代码5
    26 }

    这里面查找ThreadLocalMap的key,居然是通过value来反查的,比较少见。先看看Entry的定义吧:

    1 static class Entry extends WeakReference<ThreadLocal<?>> {
    2     /** The value associated with this ThreadLocal. */
    3     Object value;
    4 
    5     Entry(ThreadLocal<?> k, Object v) {
    6         super(k);
    7         value = v;
    8     }
    9 }

    Entry又是定义在ThreadLocalMap中的静态内部类,继承了WeakReference类,WeakReference类又继承自Reference类,在Reference类中,有一个引用变量:

    1 public abstract class Reference<T> {
    2     private T referent;
    3 }

    在Entry的构造方法中,构造新的Entry对象,referent变量存储传入的ThreadLocal对象的引用作为key,value则存储真正的值,这样将ThreadLocal对象和value的对应关系给存储下来。 
    那么我们看到上面的e.get()方法,实际上是调用的Reference类的get方法。

    代码2: 
    Reference类的get方法:

    1 public T get() {
    2     return this.referent;
    3 }

    很简单的实现,就是返回存储的referent。

    接下来先看看要对table进行rehash的条件判断和实际操作 
    代码3 
    ThreadLocal.ThreadLocalMap类的cleanSomeSlots方法

     1 private boolean cleanSomeSlots(int i, int n) {
     2     boolean removed = false;
     3     Entry[] tab = table;
     4     int len = tab.length;
     5     do {
     6         i = nextIndex(i, len);
     7         Entry e = tab[i];
     8         if (e != null && e.get() == null) { // entry不为null且entry中的key为null
     9             n = len;
    10             removed = true;
    11             i = expungeStaleEntry(i);   // 见代码4
    12         }
    13     } while ( (n >>>= 1) != 0); // 等价于n=n>>>1,>>>为无符号右移
    14     return removed;
    15 }

    该方法只是做了几次检查,没有把table整个扫一遍。源码注释的解释是说这样子性能是介于完全不检查(快速但是会遗留内存垃圾)与检查与table长度比例的元素个数(时间复杂度是O(n))之间的。这里贴出源码注释,如果有更深刻的理解可以探讨一下。 
    Heuristically scan some cells looking for stale entries. This is invoked when either a new element is added, or another stale one has been expunged. It performs a logarithmic number of scans, as a balance between no scanning (fast but retains garbage) and a number of scans proportional to number of elements, that would find all garbage but would cause some insertions to take O(n) time.

    代码4 
    ThreadLocal.ThreadLocalMap类的expungeStaleEntry方法

     1 private int expungeStaleEntry(int staleSlot) {
     2     Entry[] tab = table;
     3     int len = tab.length;
     4 
     5     // expunge entry at staleSlot
     6     tab[staleSlot].value = null;
     7     tab[staleSlot] = null;
     8     size--;     // 以上代码,将entry的value赋值为null,这样方便GC时将真正value占用的内存给释放出来;将entry赋值为null,size减1,这样这个slot就又可以重新存放新的entry了
     9 
    10     // Rehash until we encounter null
    11     Entry e;
    12     int i;
    13     for (i = nextIndex(staleSlot, len); // 从staleSlot后一个index开始向后遍历,直到遇到为null的entry
    14          (e = tab[i]) != null;
    15          i = nextIndex(i, len)) {
    16         ThreadLocal<?> k = e.get();
    17         if (k == null) {    // 如果entry的key为null,则清除掉该entry
    18             e.value = null;
    19             tab[i] = null;
    20             size--;
    21         } else {
    22             int h = k.threadLocalHashCode & (len - 1);
    23             if (h != i) {   // key的hash值不等于目前的index,说明该entry是因为有哈希冲突导致向后移动到当前index位置的
    24                 tab[i] = null;
    25 
    26                 // Unlike Knuth 6.4 Algorithm R, we must scan until
    27                 // null because multiple entries could have been stale.
    28                 while (tab[h] != null)      // 对该entry,重新进行hash并解决冲突
    29                     h = nextIndex(h, len);
    30                 tab[h] = e;
    31             }
    32         }
    33     }
    34     return i;   // 返回经过整理后的,位于staleSlot位置后的第一个为null的entry的index值
    35 }

    expungeStaleEntry方法不止清理了staleSlot位置上的entry,还把staleSlot之后的key为null的entry都清理了,并且顺带将一些有哈希冲突的entry给填充回可用的index中。

    代码5 
    ThreadLocal.ThreadLocalMap类的rehash方法

    1 private void rehash() {
    2     expungeStaleEntries();  // 见代码6
    3 
    4     // Use lower threshold for doubling to avoid hysteresis
    5     if (size >= threshold - threshold / 4)  // 进行resize的条件更苛刻了,只要大于等于3/4*threshold就进行resize
    6         resize();   // 见代码7
    7 }

    首先整理table中key为null的entry,然后进行可能的resize操作

    代码6 
    ThreadLocal.ThreadLocalMap类的expungeStaleEntries方法

    1 private void expungeStaleEntries() {
    2     Entry[] tab = table;
    3     int len = tab.length;
    4     for (int j = 0; j < len; j++) {
    5         Entry e = tab[j];
    6         if (e != null && e.get() == null)   // entry不为null且entry的key为null
    7             expungeStaleEntry(j);       // 调用代码1.4的expungeStaleEntry方法
    8     }
    9 }

    这里见到了前面分析过的expungeStaleEntry方法,也就是对table中entry进行清理。

    代码7 
    ThreadLocal.ThreadLocalMap类的resize方法

     1 private void resize() {
     2     Entry[] oldTab = table;
     3     int oldLen = oldTab.length;
     4     int newLen = oldLen * 2;
     5     Entry[] newTab = new Entry[newLen];
     6     int count = 0;
     7 
     8     for (int j = 0; j < oldLen; ++j) {
     9         Entry e = oldTab[j];
    10         if (e != null) {
    11             ThreadLocal<?> k = e.get();
    12             if (k == null) {
    13                 e.value = null; // Help the GC
    14             } else {
    15                 int h = k.threadLocalHashCode & (newLen - 1);
    16                 while (newTab[h] != null)
    17                     h = nextIndex(h, newLen);
    18                 newTab[h] = e;
    19                 count++;
    20             }
    21         }
    22     }
    23 
    24     setThreshold(newLen);
    25     size = count;
    26     table = newTab;
    27 }

    resize方法很熟悉了,将table容量翻倍,不过多分析了。

    代码8 
    最后看看ThreadLocal.ThreadLocalMap类的replaceStaleEntry方法

     1 private void replaceStaleEntry(ThreadLocal<?> key, Object value,
     2                                int staleSlot) {
     3     Entry[] tab = table;
     4     int len = tab.length;
     5     Entry e;
     6 
     7     int slotToExpunge = staleSlot;
     8     for (int i = prevIndex(staleSlot, len); // 从staleSlot位置向前找,找到最先一个需要清理的entry
     9          (e = tab[i]) != null;
    10          i = prevIndex(i, len))
    11         if (e.get() == null)
    12             slotToExpunge = i;
    13 
    14     for (int i = nextIndex(staleSlot, len);
    15          (e = tab[i]) != null;
    16          i = nextIndex(i, len)) 
    17 {
    18         ThreadLocal<?> k = e.get();
    19 
    20         if (k == key) { // 发生这种情况,说明在key本应存储的hash位置和key实际存储位置之间有出现了key为null的entry
    21             e.value = value;
    22 
    23             tab[i] = tab[staleSlot];
    24             tab[staleSlot] = e;
    25 // 这两句代码,将要清理的staleSlot位置的entry,和后面发现的因冲突而存储到i位置的两个entry进行对调
    26 
    27             if (slotToExpunge == staleSlot)
    28                 slotToExpunge = i;
    29             cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
    30             return;
    31         }
    32 
    33         if (k == null && slotToExpunge == staleSlot)
    34             slotToExpunge = i;
    35     }
    36 
    37     // If key not found, put new entry in stale slot
    38     tab[staleSlot].value = null;    // 先将原来entry的value引用断开,再讲新entry放到staleSlot位置中
    39     tab[staleSlot] = new Entry(key, value);
    40 
    41     // If there are any other stale entries in run, expunge them
    42     if (slotToExpunge != staleSlot) // 清理其他key为null的entry
    43         cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
    44 }

    这个方法比较复杂,逻辑看的有点混乱,大概是清理了一下staleSlot位置的entry,还做了进一步的清理工作,我也有点理不清楚了。如果有错误请各位读者帮忙斧正。

    ThreadLocal类的set(T value)方法就分析完了,做了两部分工作,一是把新的value和相对应的threadLocal对象存放进ThreadLocalMap中了,二就是对ThreadLocalMap中key已经为null的entry进行了清理,方便GC来回收这部分内存。

  • 相关阅读:
    SSRS Fields cannot be used in page headers or footers
    mac os x 触摸板点击无效
    Android内核sysfs中switch类使用实例
    hdu1827之强联通
    解决Gradle执行命令时报Could not determine the dependencies of task &#39;:compileReleaseJava&#39;.
    我对Lamport Logical Clock的理解
    側滑删除进阶(七、八)
    管理之路(成长之路--五)
    Qt跨平台的一个例程
    IOS 开发推荐经常使用lib
  • 原文地址:https://www.cnblogs.com/noodleprince/p/8657399.html
Copyright © 2011-2022 走看看