ThreadLocal笔记

线程类Thread包含了属性threadLocals,如下:

/* ThreadLocal values pertaining to this thread. This map is maintained
 * by the ThreadLocal class. */

ThreadLocal.ThreadLocalMap threadLocals = null;



其中K是ThreadLocal类型,而V是对应不同的value不同的类型。

可以看出ThreadLocal的value是绑定在线程Thread上的,其实它是当前线程的内部变量的意思,所有不同线程之间的变量不会相互干扰,所以它会有线程安全的作用。

我们看下ThreadLocalMap,它包含了一个Entry数组,其中Entry才是真正保存ThreadLocal和Value,如下:
static class Entry extends WeakReference<ThreadLocal> {
    /** The value associated with this ThreadLocal. */
    Object value;

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

/**
 * The table, resized as necessary.
 * table.length MUST always be a power of two.
 */
private Entry[] table;
从上面的Entry构造函数,可以知道,ThreadLocal是由弱引用关联着的,所以如果ThreadLocal在没有强引用指向的情况下会被GC回收的。
虽然Entry的Key会被回收,但如果Thread存在时间较长,那Entry的Value是不是会一直存在导致内存泄露呢?可以看ThreadLocalMap的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) {
            e.value = value;
            return;
        }

        if (k == null) {//A处
            replaceStaleEntry(key, value, i);
            return;
        }
    }

    tab[i] = new Entry(key, value);
    int sz = ++size;
    if (!cleanSomeSlots(i, sz) && sz >= threshold)//A2处
        rehash();
}
看上面的“A处”,当k == null,即当ThreadLocal被GC回收了情况下,调用了replaceStaleEntry方法,如下:
而“A2”处的cleanSomeSlots方法也会进行清除Entry工作。
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).
    int slotToExpunge = staleSlot;//C处
    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
    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) {
            e.value = value;

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

            // Start expunge at preceding stale entry if it exists
            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.
        if (k == null && slotToExpunge == staleSlot)
            slotToExpunge = i;
    }

    // If key not found, put new entry in stale slot
    tab[staleSlot].value = null;
    tab[staleSlot] = new Entry(key, value);

    // If there are any other stale entries in run, expunge them
    if (slotToExpunge != staleSlot)
        cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
看看上面的“C处”的变量slotToExpunge就是需要清除Entry的索引位置,然后会调用expungeStaleEntry方法清除Entry,方法如下:
private int expungeStaleEntry(int staleSlot) {
    Entry[] tab = table;
    int len = tab.length;

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

    // Rehash until we encounter null
    Entry e;
    int i;
    for (i = nextIndex(staleSlot, len);
         (e = tab[i]) != null;
         i = nextIndex(i, len)) {
        ThreadLocal k = e.get();
        if (k == null) {    //E0
            e.value = null; //E1
            tab[i] = null;  //E2
            size--;   //E3
        } else {
            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;
}
看看上面代码的“D1,D2,D3"处,可以看对当前的索引位置的Entry进行清除工作,并递减数量。
而"E0"处,则表示循环检查到ThreadLocal被GC回收了,则“E1,E2,E3”处会进行清除Entry的工作,并递减数量。

上面讲解了set方法,下面我们看看get方法,它会调用到ThreadLocalMap的getEntry方法,如下:
private Entry getEntry(ThreadLocal key) {
    int i = key.threadLocalHashCode & (table.length - 1);
    Entry e = table[i];
    if (e != null && e.get() == key)
        return e;
    else
        return getEntryAfterMiss(key, i, e); //F处
}
在“F处”,在找不到ThreadLocal对应的value情况下,会调用getEntryAfterMiss方法,如下:
private Entry getEntryAfterMiss(ThreadLocal key, int i, Entry e) {
    Entry[] tab = table;
    int len = tab.length;

    while (e != null) {
        ThreadLocal k = e.get();
        if (k == key)
            return e;
        if (k == null) //G处
            expungeStaleEntry(i);
        else
            i = nextIndex(i, len);
        e = tab[i];
    }
    return null;
}
在G处,k == null,则表示ThreadLocal被回收了,则会调用expungeStaleEntry方法进行Entry清除工作(在介绍ThreadLocal的set方法时我们已经介绍过expungeStaleEntry方法)

总结:
ThreadLocal在set,get方法中,如果ThreadLocal对象已经被回收了,则会进行清除Entry的工作,所以如果ThreadLocal中的value已经是无用的,就应该调用它的remove方法,将Value清除掉,当然,如果线程已经结束了,则Thread->ThreadLocalMap->Entry[]->value,这一系列的引用链都回收。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值