从 ThreadLocal 常见操作入手分析源码。

在开发过程中碰到过 ThreadLocal ,一直都没有认真看看究竟是怎么实现的,于是花了点时间理解了下,做一个笔记算是分享下。
源码基于 Android SDK 26 JDK 1.8

打算从 ThreadLocal 中的常见操作进行寻找原理,NewSetGetRemove 进行分析。如果没有耐心的看完的话,建议直接点 【二.2.3】replaceStaleEntry()


【一】ThreadLocal 结构

首先大概瞄一眼 ThreadLocal 结构。

【一】
public class ThreadLocal<T> {
    ……
    public ThreadLocal() {}
    
	static class ThreadLocalMap {
	    //【节点类】
	    static class Entry extends WeakReference<ThreadLocal<?>> {
	        /** The value associated with this ThreadLocal. */
	        Object value;
	
	        Entry(ThreadLocal<?> k, Object v) {
	            super(k);
	            value = v;
	        }
	    }
	
	    /**
	    * The initial capacity -- 【MUST be a power of two. 】
	    */
	    //【默认初始容量】
	    private static final int INITIAL_CAPACITY = 16;
	
	    /**
	    * The table, resized as necessary.
	    * table.length MUST always be a power of two.
	    */
	    //【存放节点的table】
	    private Entry[] table;
	
	    /**
	    * The number of entries in the table.
	    */
	    //【已存放节点的个数】
	    private int size = 0;
	
	    /**
	    * The next size value at which to resize.
	    */
	    //【容量预警阀值】
	    private int threshold; // Default to 0
	    ……
	}
}

首先按照我们常用的使用方式。

ThreadLocal<T> mThreadLocal = new ThreadLocal();

按照这个构造函数点进去,发现啥操作都没有。那就从常见的set入手吧。


【二】ThreadLocal.set()

【二】
public void set(T value) {
    //【新建一个线程并指向了当前线程】
    Thread t = Thread.currentThread();
    //【从当前线程中拿到 ThreadLocalMap】
    ThreadLocalMap map = getMap(t);【二.1if (map != null)
        map.set(this, value);【二.2else
        createMap(t, value);【二.3}	

然后我们来看看这三个方法。

【二.1】getMap()


【二.1】
ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

//【既然是线程里的属性,咱们就找找 Thread 有没有这个东西】
public class Thread implements Runnable {
    ……
    /* ThreadLocal values pertaining to this thread.
    * This map is maintained by the ThreadLocal class. */

    ThreadLocal.ThreadLocalMap threadLocals = null;
    ……
}	

果然有这个属性,然后在 Thread 当中查找是否有相关调用初始化
暂时没有找到,我们就默认为 null 。先看 if (map != null) 的情况。

【二.3】createMap()

【二.3void createMap(Thread t, T firstValue) {
    //【初始化t线程的ThreadLocalMap。】
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

/**
* Construct a new map initially containing (firstKey, firstValue).
* ThreadLocalMaps are constructed lazily, so we only create
* one when we have at least one entry to put in it.
*/
//【从构造方法从也看出,如果是走这个构造方法。】
//【第一次创建是拿到了一个键值对,初始化后会直接插入新数据。】
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
    //【初始化节点数组】
    table = new Entry[INITIAL_CAPACITY]; 【二.3.1】
    int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);【二.3.2//【插入第一个节点,调整节点数组大小,设置预警阀值。】
    table[i] = new Entry(firstKey, firstValue);
    size = 1;
    //【根据最大长度设置预警值】
    setThreshold(INITIAL_CAPACITY);
}

/**
* The initial capacity -- 【MUST be a power of two.】
*/
private static final int INITIAL_CAPACITY = 16;

/**
* Set the resize threshold to maintain at worst a 2/3 load factor.
*/
private void setThreshold(int len) {
    threshold = len * 2 / 3;
}

观察 ThreadLocalMap 的构造函数,是当需要开始放进数据的时候,才会初始化。

【二.3.1】INITIAL_CAPACITY

INITIAL_CAPACITY 的注释,我标记了下。

什么叫 power-of-two ,这个要是说成两种的力量?功率?

听着感觉怎么和计算机也不挂钩,咱们去google(baidu)下。

能看到一个解释类似的解释: power() :返回数字乘幂的计算结果。

咱们猜测下 power of two,是不是2的多少次方。

INITIAL_CAPACITY - 1 16 - 1 = 15。一个数好像不好说明问题,咱们多试几个2的n次方-1来试试。看看能不能找到什么规律。

3 = 22 - 1 ; 7 = 23 - 1 ; 15 = 24 - 1; 31 = 25 - 1 ; 63 = 26 - 1

然后都换成2进制看看。(只看八位)

3 = 00000011 ; 7 = 00000111 ; 15 = 00001111 ; 31 = 00011111 ; 63 = 00111111

发现0和1很整齐嘛,仿佛是有某种规律,咱们来看下下一个。 ThreadLocal.threadLocalHashCode.

【二.3.2】ThreadLocalHashCode
【二.3.2public class ThreadLocal{
    ……
    //【原来还是一个方法,那我们继续跳转。】
    private final int threadLocalHashCode = nextHashCode();
    ……
    //【调用自身的自身的hasconde获取再增加。】
    private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }

    private static AtomicInteger nextHashCode = new AtomicInteger();

    /**
    * The difference between successively generated hash codes - turns
    * implicit sequential thread-local IDs into near-optimally spread
    * multiplicative hash values for 【power-of-two-sized tables.】
    */
    private static final int HASH_INCREMENT = 0x61c88647;
    ……
}

public class AtomicInteger{

    ……
    /**
    * Atomically adds the given value to the current value.
    *
    * @param delta the value to add
    * @return the previous value
    */
    //【从这段注释来看,应该是将原值,加上delta的值。】
    public final int getAndAdd(int delta) {
        return U.getAndAddInt(this, VALUE, delta);
    }
    ……
}

不断累加 HASH_INCREMENT 作为自己的 hashCode。从刚刚的结果来看, INITIAL_CAPACITY - 1 得出了一堆 01 规律的数字,来观察下。

如果它与一个数进行 & 运算,高位的数据按位与 0 & 计算,都是 0 ;低位数据按位与 1 & 计算,都是原数据。

在这里插入图片描述
是不是这样就忽略高位,保留低位啦。这样就保证了 & 之后的数,是小于等于 len - 1。刚好也是从 table[0] ~ table[len-1]。

刚分析了 map == null 的情况,来接下来分析下,如果 map != null 的情况。

【二.2】set()

Code【二.2private void set(ThreadLocal<?> key, Object value) {
    //【指向ThreadLocalMap中的节点集合】
    Entry[] tab = table;【二.2.1】
    int len = tab.length;
    //【根据散列按位进行运算出 index。】
    int i = key.threadLocalHashCode & (len-1);
    //【从index往后循环查找。判断是先找到key,还是先碰到一个 table 中一个空的位置。】
    for (Entry e = tab[i];e != null;e = tab[i = nextIndex(i, len)]) {【二.2.2//【如果从这个循环里结束,就说明是先找到对应的节点。】
        ThreadLocal<?> k = e.get();
        //【如果发现之前ThreadLocal存储过,则修改旧值后返回。】
        if (k == key) {
            e.value = value;
            return;
        }
        //【如果是ThreadLocal == null,看名字是一些替换旧数据的操作并返回。】
        if (k == null) {
            replaceStaleEntry(key, value, i);【二.2.3return;
        }
    }

    //【如果走这,则说明先碰到 table 中空的位置,在index位置放进新数据。】
    tab[i] = new Entry(key, value);
    int sz = ++size;
    //【看名字又是一些清除的操作,进行预警值的判断之后还有一次rehash()操作。】
    if (!cleanSomeSlots(i, sz) && sz >= threshold)
        rehash();【二.2.4}	    

好吧,发现这次挑战要多一点。一个一个看。

【二.2.1】ThreadLocal.ThreadLocalMap.Entry
【二.2.1//需要说明的就是,键是ThreadLocal类型,并且是弱引用的.
static class Entry extends WeakReference<ThreadLocal<?>> {
    /** The value associated with this ThreadLocal. */

    Object value;

    Entry(ThreadLocal<?> k, Object v) {
        super(k);
        value = v;
    }
}

来看个小例子,比如咱们先这么操作下,建两个 ThreadLocal

//【新建两个ThreadLocal,并存放不同的类。】
ThreadLocal<String> t1 = new ThreaLocal();
ThreadLocal<Integer> t2 = new ThreaLocal();
//【thread1 】
t1.set("One");
t2.set(1);
//【thread2】
t1.set("Two");
t2.set(2);
//【然后两个 Thread Entry[] tables 应该就差不多是这种.】
//【thread1】
Entry[] table = [<t1,"One">,<t2,1>];
//【thread2】
Entry[] table = [<t1,"Two">,<t2,2>];

//【测试下,贴部分代码 安卓下测试的。】
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //【主线程设置一次】
    t1.set("One");
    t2.set(1);
    new Thread(new Runnable() {
        @Override
        public void run() {
            //【新开线程再设置一次】
            t1.set("Two");
            t2.set(2);
            //【新线程取一次结果】
            Log.w(TAG, " new Thread t1.get() : " + t1.get() + " ; t2.get() : " + t2.get());
        }
    }).start();
    //【主线程再取一次结果】
    Log.w(TAG, "main Thread t1.get() : " + t1.get() + " ; t2.get() : " + t2.get());
}  

来运行看看结果。

**

取值的时候就会先拿到对应线程的 ThreaLocalMap ,再通过对比 table 中每个节点中 key 的值,获得对应的值。

【二.2.2】nextIndex()
【二.2.2private static int nextIndex(int i, int len) {
    return ((i + 1 < len) ? i + 1 : 0);
}

这个方法简单,小于长度时加1向后移动,不过那如果等于长度之后,就返回0.是不是可以理解为,向后一直循环,满了之后又从0开始,是一个循环的数组?

table[0] ~ table[len-1] -> table[0] 从 0 到末尾,又重新指向 0。

【二.2.3】replaceStaleEntry()
【二.2.3private void replaceStaleEntry(ThreadLocal<?> key, Object value,int staleSlot) {
    Entry[] tab = table;
    int len = tab.length;
    Entry e;

    //【先存放原计划 index】
    int slotToExpunge = staleSlot;
    //【向前循环寻找,是否存在节点的键为 null ,如果存在则向左一直查找并存储最靠左的 index,直到节点指向了一个 null 的位置】
    //【这个和之前的nextIndex()差不多。这个是向前循环】
    for (int i = prevIndex(staleSlot, len);(e = tab[i]) != null;i = prevIndex(i, len))
        if (e.get() == null)
            slotToExpunge = i;

    //【从原计划 index 向后查找】
    for (int i = nextIndex(staleSlot, len);(e = tab[i]) != null;i = nextIndex(i, len)) {
        ThreadLocal<?> k = e.get();

        // If we find key, then we need to swap it
        // with the stale entry to【maintain hash table order.】
        // The newly stale slot, or any other stale slot
        // encountered above it, can then be sent to expungeStaleEntry
        // to remove or rehash all of the other entries in run.

        if (k == key) {
            //【如果判断是相同的key,则先替换旧值,将之前在原计划index的数据,移到key相等的位置】
            //【再把替换过的节点插入到原计划index 以保证之前的hash顺序一致。如上的注释】
            e.value = value;
            tab[i] = tab[staleSlot];
            tab[staleSlot] = e;

            // Start expunge at preceding stale entry if it exists
            //【如果上一步向左扫描都没有节点键为null的情况,因为 staleSlot 目前没有改变】
            //【反推如果 slotToExpunge == staleSlot 成立,则说明上一步向左扫描没有找到节点的键为null情况(碰到null节点前)】
            if (slotToExpunge == staleSlot)
                slotToExpunge = i;
            //【将i的值作为清除的index传入,就是两种情况,左边有节点键为null的index,或者此处交换之后的index】
            cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
            return;
        }

        // If we didn't find stale entry on backward scan, the
        // first stale entry seen while scanning for key is the
        // first still present in the run.
        //【如果没有找到,slotToExpunge 则等于从staleSlot右边算,第一个碰到节点键为null的index】
        if (k == null && slotToExpunge == staleSlot)
            slotToExpunge = i;
    }

    // If key not found, put new entry in stale slot
    //【如果没有找到该ThreadLocal,则在原计划位置插入新Enrty】
    tab[staleSlot].value = null;
    tab[staleSlot] = new Entry(key, value);

    // If there are any other stale entries in run, expunge them
    //【如果两个数据不相等则说明右边存在键为null的Enrty,然后从那个index开始清除】
    if (slotToExpunge != staleSlot)
        cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);*}

好吧,长方法又来了 ……
在这里插入图片描述
不过 … 纵使困顿难行,亦当砥砺奋进嘛。

  • 先存放最先计划替换的 index ,先向左查询,判断是否有键为 null 的节点,有的话,就替换一次 slotToExpunge 的值,一直查找存储最左边的,直到碰到
    null 的位置。
  • 向右查找,是否存在 key 相同的节点。
    • 如果向右能找到,则替换节点 value ,并且与 staleSlot 位置进行交换,保证之前的散列顺序,然后从 slotToExpunge 开始清理。
    • 如果不能找到,判断上一步是否在左边查找到键为 null 的节点,如果没有向左移动过,则从 staleSlot + 1 处开始清理。
  • 如果没有找到节点,则在最开始位置进行插入数据,并判断是否需要清理
    • 如果向左和向右查找的时候,都是正常的话,那么 staleSlot == staleToExpunge ,则不需要清理。
    • 否则就从 slotToExpunge 开始清理。

好吧,文字描述了,估计还是有点抽象,还是来几张图好说明一下。先分析第一个循环,向左循环查找。

接下来分析后面的循环,向右循环查找。

关于 staleToExpunge ,只要它向左移动过之后,清理肯定是从左开始的,并且因为中间是连续的,所以与 staleSlot 的位置就没有关系了。

把这个拿下之后,就大概能明白清理的思路了,剩下就是分析清理的方法了 expungeStaleEntry()cleanSomeSlots()

*/**
* Expunge a stale entry by rehashing any possibly colliding entries
* lying between staleSlot and the next null slot.  This also expunges
* any other stale entries encountered before the trailing null.  See
* Knuth, Section 6.4
*
* @param staleSlot index of slot known to have null key
* @return the index of the next null slot after staleSlot
* (all between staleSlot and this slot will have been checked
* for expunging).
*/
private int expungeStaleEntry(int staleSlot) {
    Entry[] tab = table;
    int len = tab.length;

    // expunge entry at staleSlot.
    //【注意】这里是先置空value,再置空key。
    tab[staleSlot].value = null;
    tab[staleSlot] = null;
    size--;

    // Rehash until we encounter null
    Entry e;
    int i;
    //【从要清除的index开始向后扫描】
    for (i = nextIndex(staleSlot, len);(e = tab[i]) != null;i = nextIndex(i, len)) {
        ThreadLocal<?> k = e.get();
        //【如果碰到节点键为null,会释放掉值,并置空table[i].调整table大小】
        if (k == null) {
            e.value = null;
            tab[i] = null;
            size--;
        } else {
            int h = k.threadLocalHashCode & (len - 1);
            //【如果碰到键不为null,则会重新算出新index,如果不在原来的位置,置空原位置,就线性向后一直探测到null节点并放入】
            if (h != i) {
                tab[i] = null;
                // Unlike Knuth 6.4 Algorithm R, we must scan until
                // null because multiple entries could have been stale.
                //【向后探测直到存在null的位置放入数据】
                while (tab[h] != null)
                    h = nextIndex(h, len);
                tab[h] = e;
            }
        }
    }
    return i;
}

此处返回的 i,已经是 for 循环不成立的时候,就是碰到空节点的时候。

*private boolean cleanSomeSlots(int i, int n) {
    boolean removed = false;
    Entry[] tab = table;
    int len = tab.length;
    do {
        i = nextIndex(i, len);
        Entry e = tab[i];
        if (e != null && e.get() == null) {
            n = len;
            removed = true;
            i = expungeStaleEntry(i);
        }
    } while ( (n >>>= 1) != 0);
    return removed;
}   

从刚刚调用时传入的数值。 cleanSomeSlots(expungeStaleEntry(slotToExpunge), len) ;

expungeStaleEntry() 返回为一个空键节点 indexcleanSomeSlots() 则从 index 下一个开始查找。

如果查找到的节点不为 null ,但是键为 null ,则从该处开始清理数据。

清理一次,则 n 向右移一位,table 大小缩小一半( 1 变 0 肯定是不算哈)。

其实此处没太想通退出循环的条件是连续 logN 次 没找到键为 null 的节点。

有个小细节:nextIndexpreIndex 为什么从 ±1开始计算,而不是从传入的值计算,从方法的调用来看。
传入的一般是节点为 null index ,如果直接从 index 开始进行循环查找,则直接就中断了。

【二.2.4】rehash()
【二.2.4private void rehash() {
//【清理所有老旧的数据(即键为null的节点。)】
    expungeStaleEntries();

    // Use lower threshold for doubling to avoid hysteresis
    //【如果清理之后,仍大于预警值的3/4,则两倍扩容】
    if (size >= threshold - threshold / 4)
        resize();
}

/**
* Expunge all stale entries in the table.
*/
//【循环查找清理】
private void expungeStaleEntries() {
    Entry[] tab = table;
    int len = tab.length;
    for (int j = 0; j < len; j++) {
        Entry e = tab[j];
        if (e != null && e.get() == null)
            expungeStaleEntry(j);
    }
}

/**
* Double the capacity of the table.
*/
private void resize() {
    Entry[] oldTab = table;
    int oldLen = oldTab.length;
    int newLen = oldLen * 2;
    Entry[] newTab = new Entry[newLen];
    int count = 0;

    for (int j = 0; j < oldLen; ++j) {
        Entry e = oldTab[j];
        if (e != null) {
            ThreadLocal<?> k = e.get();
            if (k == null) {
                e.value = null; // Help the GC【帮助垃圾回收】
            } else {
                int h = k.threadLocalHashCode & (newLen - 1);
                //【向后线性探测null位置插入节点】
                while (newTab[h] != null)
                    h = nextIndex(h, newLen);
                newTab[h] = e;
                count++;
            }
        }
    }
    //【设置预警值】
    setThreshold(newLen);
    size = count;
    table = newTab;
}

set 方法就差不多分析完了,真的是有点长,不过基本把前面的思路理清之后,后面的几个方法也没啥难度了。

说完 set 肯定是有 get 的。

【三】ThreadLocal.get()


Code【三】
public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        //【和前面set一样,如果ThreadLocalMap != null &&
        // ThreadLocalMap.get() != null ,会根据键进行对应的查找,并向上转型为T返回。】
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    //【如果ThreadLocalMap == null 或者 ThreadLocalMap.get() == null.】
    //【则进行返回初始化值】
    return setInitialValue();
}

//【接下来看看初始化值是怎么回事】
private T setInitialValue() {
    //【默认返回null】
    T value = initialValue();
    Thread t = Thread.currentThread();
    //【从线程t中查找是否ThreadLocalMap == null ?】
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
    return value;
}

//【说明第一次初始化时,都是 null,无论后面 map 是否为 null】
protected T initialValue() {
    return null;
}

createMap() 在【二.3】中已经分析过了。

map.set(this, value) 在【二.2】中已经分析过了,类似与 set 方法。

接下来看 remove()

【四】ThreadLocal.remove()


Code【四】
public void remove() {
    //【获取当前线程的ThreadLocalMao,如果存在则根据当前的ThreadLocal查找值】
    ThreadLocalMap m = getMap(Thread.currentThread());
    if (m != null)
        m.remove(this);
}

/**
* Remove the entry for key.
*/
private void remove(ThreadLocal<?> key) {
    Entry[] tab = table;
    int len = tab.length;
    //【根据hash值算出index】
    int i = key.threadLocalHashCode & (len-1);
    for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) {
        if (e.get() == key) {
            //【找到节点后,清除该节点,并从从该位置向后清理】
            e.clear();
            expungeStaleEntry(i);
            return;
        }
    }
}

到这基本就算分析完了,主要的是 replaceStaleEntry() 方法,如果把这个理解透的话,基本就差不多明白了。

留一个问题:前面一直在说节点键为 null 的情况,有没有反应过来什么情况下节点的键为 null ,如果没有反应过来的话。

可以去看下 ThreadLocalMap.Entry 看了构造函数之后应该就能明白了。

【五】总结:

  • 在每个线程中都存在一个 ThreadLocalMap ,它有一个节点数组 Entry<ThreadLocal,value>[],每个 ThreadLocal 就是对应的键, T 就是对应的 value 类型。

  • ThreadLocal 会在插入新数据时会清理老旧的数据。如果不及时清理,一是影响了后续数据的插入,二是影响了 value 的回收。

  • 其他容器类也存在长度为 2 的指数情况,通过 hash值len - 1 来获取数据存放的 index

  • ThreadLocal 只是类似在每个线程都存放一个自己能使用的变量,如果你需要多个线程读写同一个数据,那么还是需要用 锁 机制或者 CAS 操作来保证数据的同步与正确性。

能力有限,可能存在一些问题或者不足之处,烦请指出,感谢。

要是觉得可以的话,麻烦点个赞表示支持。😂

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章