ThreadLocal源码分析

//使用泛型
public class ThreadLocal<T> {

//空实现
public ThreadLocal() {
    }

public void set(T value) {
        Thread t = Thread.currentThread();
        //ThreadLocalMap是核心对象
        ThreadLocalMap map = getMap(t);
        //为空则创建,否则设置value
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

先看createMap

void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

这里看到创建的ThreadLocalMap赋值给了Thread的threadLocals。

public
class Thread implements Runnable {

/* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

每个线程维护一个自己的ThreadLocalMap,接下来分析ThreadLocalMap。

静态内部类
static class ThreadLocalMap {

    //ThreadLocal作为key采用弱引用
    static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

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

    private static final int INITIAL_CAPACITY = 16;

    private Entry[] table;
    
    ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
            //
            table = new Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }

Entry数组,始化大小为16,然后是生成散列后的位置i,这里继续分析firstKey.threadLocalHashCode。

//final修饰的int类型
private final int threadLocalHashCode = nextHashCode();

//这个值为了散列均匀,2的32次方乘以黄金分割
private static final int HASH_INCREMENT = 0x61c88647;

    /**
     * Returns the next hash code.
     */
    //每次调用+1
    private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }

这里第一个值就已经放入了i位置,继续看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;
            //同样先计算散列位置i
            int i = key.threadLocalHashCode & (len-1);
            之后从i位置遍历数组
            for (Entry e = tab[i];
                 e != null;
                 //nextIndex简单粗暴直接+1
                 e = tab[i = nextIndex(i, len)]) {
                //从数组里获取当前元素的key
                ThreadLocal<?> k = e.get();
                //相等说明同一个key直接替换value
                if (k == key) {
                    e.value = value;
                    return;
                }
                //key是null,但是value有值,需要清空垃圾避免内存泄漏,稍后分析
                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }
            //走到这说明找到了能存放的空位置,
            tab[i] = new Entry(key, value);
            int sz = ++size;
            //先清理垃圾,然后判断是否超过加载因子的阈值,是否需要扩容   
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }


private static int nextIndex(int i, int len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }
//旧的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;
            //往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
            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则交换,保证散列顺序
                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;
            }
            //走到这说明没找到一样的key,直接清除替换
            // 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);
        }
//清理
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;
        }


private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;
            //先清理槽位
            // expunge entry at staleSlot
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;
            //然后重新hash
            // 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) {
                    e.value = null;
                    tab[i] = null;
                    size--;
                } 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;
        }

接着看rehash

setThreshold(INITIAL_CAPACITY);

private void setThreshold(int len) {
            //默认是初始长度的三分之二
            threshold = len * 2 / 3;
        }

private void rehash() {
            expungeStaleEntries();
            
            // Use lower threshold for doubling to avoid hysteresis
            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;
            //遍历重新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; //帮助GC
                    } else {
                        int h = k.threadLocalHashCode & (newLen - 1);
                        while (newTab[h] != null)
                            h = nextIndex(h, newLen);
                        newTab[h] = e;
                        count++;
                    }
                }
            }
            //重设threshold
            setThreshold(newLen);
            size = count;
            table = newTab;
        }

继续分析get

public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }


private Entry getEntry(ThreadLocal<?> key) {
            int i = key.threadLocalHashCode & (table.length - 1);
            Entry e = table[i];
            //命中就返回e
            if (e != null && e.get() == key)
                return e;
            else
                return getEntryAfterMiss(key, i, e);
        }

//没有命中就继续遍历
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)//如果key是空,说明泄露了,就清理
                    expungeStaleEntry(i);
                else
                    i = nextIndex(i, len);
                e = tab[i];
            }
            return null;
        }

总结:

每个Thread持有自己的ThreadLocalMap,所以线程间数据隔离。

内存泄漏问题:

假设场景:A类调用ThreadLocal的set方法,在当前线程Thread中两条引用关系如下:强引用链:A->Thread->ThreadLocalMap->Entry->Value;弱引用链:ThreadLocal->Entry。

随着A类执行完后,引用关系结束,GC扫描把弱引用链Entry的key中ThreadLocal回收,但是value还长时间存在,直到Thread被回收,发生内存泄漏。

解决办法:虽然set等方法也会触发expungeStaleEntry等回收操作,但是原则上

使用完ThreadLocal后应该立即remove。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值