ThreadLocal原理

ThreadLocal和Thread关系:

Thread中维护了一个ThreadLocalMap,key是ThreadLocal,value是要存储的数据副本,每次存取ThreadLocal,都是从当前线程中的ThreadLocalMap找对应ThreadLocal的key对应的value;

key为什么被设计为弱引用?

回归本质,ThreadLocalMap是用来存放对象的,在一次线程的执行栈中,存放数据后方便我们在任意的地方取得我们想要的值而不被其他线程干扰。ThreadLocalMap本身并没有为外界提供取出和存放数据的API,我们所能获得数据的方式只有通过ThreadLocal类提供的API来间接的从ThreadLocalMap取出数据,所以,当我们用不了key(ThreadLocal对象)的API也就无法从ThreadLocalMap里取出指定的数据。

在上面的例子中,A对象被回收了,这些get和set方法也访问不到了,也就没法从ThreadLocalMap里取出数据了。没法利用API取出数据,那这个Entry对象还有用吗??所以最好的方法是在A对象被回收后,系统自动回收对应的Entry对象,但是让Entry对象或其中的value对象做为弱引用都是非常不合理的。所以,让key(threadLocal对象)为弱引用,自动被垃圾回收,key就变为null了,下次,我们就可以通过Entry不为null,而key为null来判断该Entry对象该被清理掉了。

至于ThreadLocalMap为什么不给外界提供API来操作数据,我觉得是因为这个Map对于一个线程只有一份,任何地方都在用,为了提供更方便的API和为了我们不破换其他框架保存到里面的数据,所以才用ThreadLocal作为key和API来操作数据。

1.查询方法:

private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
    Entry[] tab = table;
    int len = tab.length;
//开放地址法,从定位到的hash桶位置循环遍历hash冲突的entry
    while (e != null) {
        ThreadLocal<?> k = e.get();
        if (k == key)//找到key直接返回
            return e;
        if (k == null)//发现脏entry进行清除,清除后继续从该位置往后遍历
    	expungeStaleEntry(i);
        else
            i = nextIndex(i, len);
        e = tab[i];
    }
    return null;
}
2.remove方法:

private void remove(ThreadLocal<?> key) {
    Entry[] tab = table;
    int len = tab.length;
    int i = key.threadLocalHashCode & (len-1);
    for (Entry e = tab[i];
         e != null;
         e = tab[i = nextIndex(i, len)]) {
        if (e.get() == key) {//从桶位置开始往后遍历,清除key
            e.clear();
            expungeStaleEntry(i);
            return;
        }
    }
}
3.set方法:

private void set(ThreadLocal<?> key, Object value) {

    // We don't use a fast path as with get() because it is at
    // least as common to use set() to create new entries as
    // it is to replace existing ones, in which case, a fast
    // path would fail more often than not.

    Entry[] tab = table;
    int len = tab.length;
    int i = key.threadLocalHashCode & (len-1);

    for (Entry e = tab[i];
         e != null;
         e = tab[i = nextIndex(i, len)]) {
        ThreadLocal<?> k = e.get();

        if (k == key) {//桶位置循环往后遍历,找到相同key,直接覆盖返回
            e.value = value;
            return;
        }

        if (k == null) {//找到脏entry直接替换返回
    	replaceStaleEntry(key, value, i);
            return;
        }
    }
    //如果既没找到相同key,也没找到脏entry,直接开放地址法在最后一个null位置添加
    tab[i] = new Entry(key, value);
    int sz = ++size;
    //添加完成,判断一下是否需要重新hash扩容
    if (!cleanSomeSlots(i, sz) && sz >= threshold)
        rehash();
}
替换方法:
private void replaceStaleEntry(ThreadLocal<?> key, Object value,
                               int staleSlot) {
    Entry[] tab = table;
    int len = tab.length;
    Entry e;

    // Back up to check for prior stale entry in current run.
    // We clean out whole runs at a time to avoid continual
    // incremental rehashing due to garbage collector freeing
    // up refs in bunches (i.e., whenever the collector runs).
    //先找到当前桶前面最近的一个脏entry,没有那么就是当前桶自身
    int slotToExpunge = staleSlot;
    for (int i = prevIndex(staleSlot, len);
         (e = tab[i]) != null;
         i = prevIndex(i, len))
        if (e.get() == null)
            slotToExpunge = i;

    // Find either the key or trailing null slot of run, whichever
    // occurs first
    //从当前桶位置循环往后遍历,直到null停止
    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.
        //如果找到相同key,直接覆盖value,同时将该entry和当前桶位置调换位置
        if (k == key) {
            e.value = value;

            tab[i] = tab[staleSlot];
            tab[staleSlot] = e;

            // Start expunge at preceding stale entry if it exists
            //如果当前桶左边最近的脏entry就是当前桶,因为当前桶和右边的entry交换位置,所以脏entry就是当前循环的位置,最后清除脏entry
    	if (slotToExpunge == staleSlot)
                slotToExpunge = i;
            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.
        //找到另一个脏entry,同时当前桶左边最近的脏entry就是当前桶,那么清除的脏key就是当前遍历的脏entry
        if (k == null && slotToExpunge == staleSlot)
            slotToExpunge = i;
    }

    // If key not found, put new entry in stale slot
    //上面循环退出,运行外面逻辑情况是没有找到相同key,那么直接在当前入口entry进行替换
    tab[staleSlot].value = null;
    tab[staleSlot] = new Entry(key, value);

    // If there are any other stale entries in run, expunge them
    //待清除的脏entry不是入口entry,则进行清除,因为当前entry替换为一个非脏entry
    if (slotToExpunge != staleSlot)
        cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
清除方法:因为使用开放地址法存储,判断是否结束是当前entry不为null,所以hash碰撞的entry必须是连续存储的,如果不连续循环判断是否存在相同key就会中断,会出现存储多个相同key的entry,所以expungeStaleEntry方法从入口hash桶位置循环遍历,直到找到null结束,如果找到脏entry则置空,否则有hash值获取桶的开始位置,向后遍历找到空的桶,将当前正常的entry放到左边的冲突位置null的桶中,实现hash冲突entry存储连续

private int expungeStaleEntry(int staleSlot) {
    Entry[] tab = table;
    int len = tab.length;

    // expunge entry at staleSlot
    tab[staleSlot].value = null;
    tab[staleSlot] = null;
    size--;

    // Rehash until we encounter null
    Entry e;
    int i;
    //入口hash桶位置循环遍历
    for (i = nextIndex(staleSlot, len);
         (e = tab[i]) != null;
         i = nextIndex(i, len)) {
        ThreadLocal<?> k = e.get();
        //找到脏entry则置空
        if (k == null) {
            e.value = null;
            tab[i] = null;
            size--;
        } else {
            //有hash值获取桶的开始位置,有h != i判断是碰撞存储,所以从冲突最开始的位置向后遍历找到空的桶,将当前正常的entry放到左边的冲突位置null的桶中,实现hash冲突entry存储连续
            int h = k.threadLocalHashCode & (len - 1);
            if (h != i) {
                tab[i] = null;

                // Unlike Knuth 6.4 Algorithm R, we must scan until
                // null because multiple entries could have been stale.
                while (tab[h] != null)
                    h = nextIndex(h, len);
                tab[h] = e;
            }
        }
    }
    return i;
}
从当前位置向后遍历,遇到脏entry就执行上面方法,清除脏entry,同时整理冲突存储entry,保证连续存储
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;
}
rehash逻辑:
set值如果没有清除entry,要判断当前tab大小时候大于等于threshold(threshold = len * 2 / 3),大于等于就执行rehash

if (!cleanSomeSlots(i, sz) && sz >= threshold)
    rehash();

private void rehash() {
    //Expunge all stale entries in the table,对所有tab的entry进行无效entry清除,注意和上面指定位置清除区别
    expungeStaleEntries();

    // Use lower threshold for doubling to avoid hysteresis
    //size大于等于3/4的threshold进行扩容
    if (size >= threshold - threshold / 4)
        resize();
}

private void resize() {
    Entry[] oldTab = table;
    int oldLen = oldTab.length;
    //扩容为原来两倍
    int newLen = oldLen * 2;
    Entry[] newTab = new Entry[newLen];
    int count = 0;
    //所有entry重新hash定位到新的位置
    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);
                while (newTab[h] != null)
                    h = nextIndex(h, newLen);
                newTab[h] = e;
                count++;
            }
        }
    }

    setThreshold(newLen);
    size = count;
    table = newTab;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值