ThreadLocal

TreadLocal阅读笔记

二、类结构

1578810641152

ThreadLocal中嵌套内部类ThreadLocalMap,这个类本质上是一个Map,和HashMap之类的实现相似,依然是key-value的形式,其中有一个内部类Entry,其中key可以看做是ThreadLocal实例,但是本质是持有ThreadLocal实例的弱引用。

三、存储结构

  • 每个Thread线程内部都有一个Map
  • Map里面存储线程本地对象(key)和线程的变量副本(value)
  • 但是Thread内部的Map是由ThreadLocal维护的,由ThreadLocal负责向Map获取和设置线程的副本变量值
  • 所以对于不通的线程,每次获取副本值时,别的线程并不能获取到当前线程的副本之,形成了副本的隔离,互不干扰

四、源码分析

内部类
ThreadLocalMap
1、ThreadLocalMap内部类-属性
  • // 默认容量大小-16
    private static final int INITIAL_CAPACITY = 16;
    // 元素数组
    private Entry[] table;
    // 当前容量大小
    private int size = 0;
    // 扩容的阀值
    private int threshold; // Default to 0
    
2、ThreadLocalMap内部类-子类
  • static class Entry extends WeakReference<ThreadLocal<?>> {
        /** The value associated with this ThreadLocal. */
        Object value;
    
        Entry(ThreadLocal<?> k, Object v) {
            super(k);
            value = v;
        }
    }
    
3、ThreadLocalMap内部类-构造器
  • /** 初始化构造器:会初始化一个元素*/
    ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
        // 初始化表
        table = new Entry[INITIAL_CAPACITY];
        // 计算索引
        int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
        // 生成Entry对象,并保存咋表的索引中
        table[i] = new Entry(firstKey, firstValue);
        // 初始化元素后,默认size = 1
        size = 1;
        // 设置下一次扩容的阔值
        setThreshold(INITIAL_CAPACITY);
    }
    
    /** 初始化构造器:根据传入的ThreadLocalMap来初始化 */
    private ThreadLocalMap(ThreadLocalMap parentMap){
        // 根据TreadLocalMap 参数 初始化表
        Entry[] parentTable = parentMap.table;
        // 获取参数表的大小
        int len = parentTable.length;
        // 根据上面获取的大小初始化
        setThreshold(len);
        table = new Entry[len];
    
        // 循环获取元素
        for (int j = 0; j < len; j++) {
            Entry e = parentTable[j];
            if (e != null) {
                @SuppressWarnings("unchecked")
                ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
                if (key != null) {
                    Object value = key.childValue(e.value);
                    Entry c = new Entry(key, value);
                    int h = key.threadLocalHashCode & (len - 1);
                    // 如果当前由元素,就循环到最后
                    while (table[h] != null)
                        /*
                   		private static int nextIndex(int i, int len) {
                   			// 下一个就是索引 + 1 ,超出就索引为0
                			return ((i + 1 < len) ? i + 1 : 0);
            			}
                        */
                        // 次数是不会出现索引被占用,因为本身就是创建的一样大的空数组
                        h = nextIndex(h, len);
                    // 此时table[h] 肯定是null,所以直接把c赋值
                    table[h] = c;
                    size++;
                }
            }
        }
    }
    
    4、ThreadLocalMap内部类-主要方法

环形索引函数

  • /** 获取当前索引下一个索引,处理了边界问题 */
    private static int nextIndex(int i, int len) {
        return ((i + 1 < len) ? i + 1 : 0);
    }
    
    /** 获取当前索引上一个索引,处理了边界问题 */
    private static int prevIndex(int i, int len) {
        return ((i - 1 >= 0) ? i - 1 : len - 1);
    }
    
    

getXXX函数

  • 
    /** 根据传入的线程,获取对应的Entry() */
    private Entry getEntry(ThreadLocal<?> key) {
        int i = key.threadLocalHashCode & (table.length - 1);
        Entry e = table[i];
        if (e != null && e.get() == key)
            // 对应的entry存在且未失效且弱引用指向的ThreadLocal就是key,则命中返回
            return e;
        else
            // 因为用的是线性探测,所有往后找还是有可能能够找到目标Entry值
            return getEntryAfterMiss(key, i, e);
    }
    
    /** 调动getEntry未直接命中搞得时候调用此方法 */
    private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
        Entry[] tab = table;
        int len = tab.length;
    
       // 基于线性探测法不断向后探测直到遇到空Entry
        while (e != null) {
            ThreadLocal<?> k = e.get();
            if (k == key)
                // 找到目标
                return e;
            if (k == null)
                // 该entry对应的ThreadLocal已经被回收,
                // 调用expungeStaleEntry来清理无效的entry
                expungeStaleEntry(i);
            else
                // 继续找下一个索引
                i = nextIndex(i, len);
            e = tab[i];
        }
        return null;
    }
    
    /**
     * 这个函数是ThreadLocal的核心清理函数,它做的事情很简答:
     * 就是从staleSlot开始遍历,将无效(弱引用指向对象被回收)清理,
     * 即对应entry中的value置为null,将指向这个entry的table[i]置为null,直到扫到空Entry
     * 另外,在过程中还会对费控的entry作rehash
     * 可是说这个函数的作用就是从staleSlot开始清理连续段中的slot(断开强引用,rehash slot等)
     */
    private int expungeStaleEntry(int staleSlot) {
        Entry[] tab = table;
        int len = tab.length;
    
        // 因为entry对应的 ThreadLocal 已被回收,value 设为null,显式断开强引用
        // expunge entry at staleSlot
        tab[staleSlot].value = null;
        // 显式设置该entry 为 null,以便垃圾回收
        tab[staleSlot] = null;
        size--;
    
        // 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) {
                // 清理对应ThreadLocal已被回收的entry
                e.value = null;
                tab[i] = null;
                size--;
            } else {
                // 对于还没有被回收的情况,需要做一次rehash
                // 如果对应的ThreadLocal 的ID 对len取模出来的索引 h 不为当前位置 i,
                // 则从h 向后线性探测到第一个空的slot,把当前的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;
                }
            }
        }
        // 返回staleSlot之后第一个空的slot索引
        return i;
    }
    

set、replaceStaleEntry、cleanSomeSlots函数

  • 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) {
                replaceStaleEntry(key, value, i);
                return;
            }
        }
    
        tab[i] = new Entry(key, value);
        int sz = ++size;
        if (!cleanSomeSlots(i, sz) && sz >= threshold)
            rehash();
    }
    
    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;
    }// 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();
        // 找到对应的entry
        if (k == key) {
            e.value = value;
            return;
        }
        // 替换失效的entry
        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 void replaceStaleEntry(ThreadLocal<?> key, Object value,
                                   int staleSlot) {
        Entry[] tab = table;
        int len = tab.length;
        Entry e;
        // 向前扫描,找到最前的一个无效slot
        // 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;
        for (int i = prevIndex(staleSlot, len);
             (e = tab[i]) != null;
             i = prevIndex(i, len))
            if (e.get() == null)
                slotToExpunge = i;
    
        // 向后遍历table
        // 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,将其与无效的slot交换
            if (k == key) {
                // 更新对应slot的value值
                e.value = value;
    
                tab[i] = tab[staleSlot];
                tab[staleSlot] = e;
    
                // Start expunge at preceding stale entry if it exists
                /* * 如果在整个扫描过程中(包含函数一开始向前扫描与 i 之前的向后扫描)
                   * 找到了之前无效slot则以那个位置作为清理点
                   * 否则别以当前的i作为清理节点
                   */
                if (slotToExpunge == staleSlot)
                    slotToExpunge = i;
                // 从slotToExpunge 开始做一次联系段的清理,再做一次启发式清理
                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.
            // 如果当前的slot 已失效,并且向前扫描过程中没有无效的slot,
            // 则更新slotToExpunge为当前变量
            if (k == null && slotToExpunge == staleSlot)
                slotToExpunge = i;
        }
    
        // If key not found, put new entry in stale slot
        // 如果key在table 中不存在,则在原地放一个即可
        tab[staleSlot].value = null;
        tab[staleSlot] = new Entry(key, value);
    
        // If there are any other stale entries in run, expunge them
        // 在探测过程中如果发现倔强的slot,则不做清理(联系段清理+启发式清理)
        if (slotToExpunge != staleSlot)
            cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
    }
    /*
    启发式地清理slot
    i 对饮gentry是非无效(指向的ThreadLocal没回收,或entry本身为空)
    n 是用于控制控制扫描次数的
    正常情况下如果log n 次扫描没有发现无效的slot,函数就结束了
    但是如果发现了无效的slot,将 n 置为table 的长度len,做一次连续段的清理了
    再从下一个空的slot 开始继续扫描
    
    这个函数有两处地方会都被调用,一处是插入的时候可能会被调用,另外一个是在替换无效slot的时候可能会被调用,区别是前者传入 的n为元素个数,厚泽为table的容量
    */
    private boolean cleanSomeSlots(int i, int n) {
        boolean removed = false;
        Entry[] tab = table;
        int len = tab.length;
        do {
            // i 在任何情况下自己都不会是一个无效的slot,所以从下一个开始判断
            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 void rehash() {
        // 做一次全量清理
        expungeStaleEntries();
        // 因为做了一次清理,所以size很可能会变小。
        // ThreadLocalMap这里的实现调低阔值来判断是否需要扩容
        // threshold默认为len*2/3,所以这里的threshold - threshold / 4 相当于 len / 2
        // Use lower threshold for doubling to avoid hysteresis
        if (size >= threshold - threshold / 4)
            resize();
    }
    
    /** 做一次全量清理 */
    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);
        }
    }
    
    /** 扩容,因为需要保证table的容量len 为2的幂数,所以扩容既扩大2倍  */
    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 {
                    // 线性探测来存放Entry
                    int h = k.threadLocalHashCode & (newLen - 1);
                    while (newTab[h] != null)
                        h = nextIndex(h, newLen);
                    newTab[h] = e;
                    count++;
                }
            }
        }
    
        setThreshold(newLen);
        size = count;
        table = newTab;
    }
    

remove函数

  • // 删除map中的ThreadLocal
    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) {
                // 显式断开弱引用
                e.clear();
                // 进行段清理
                expungeStaleEntry(i);
                return;
            }
        }
    }
    
属性
/** 自身的hashCode值,用于-例:(threadLocalHashCode & (INITIAL_CAPACITY - 1) */
private final int threadLocalHashCode = nextHashCode();
/** 下一个要给出的hash值 */
private static AtomicInteger nextHashCode = new AtomicInteger();
/** 
 * 生成hash code 间隙的这个魔法值
 * 可以让生成出来的值或ThreadLocal的Id较为均匀地分布在2的幂大小的数组中 
 */
private static final int HASH_INCREMENT = 0x61c88647;
/** 返回下一个hash散列值 */
private static int nextHashCode() {
    return nextHashCode.getAndAdd(HASH_INCREMENT);
}
构造
public ThreadLocal() {}
主要方法
  • 基本都是对ThreadLocalMap的操作
/** 为当前线程初始化副本变量值 */
public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
    return new SuppliedThreadLocal<>(supplier);
}

/** 获取当前线程的副本变量值 */
public T get() {
    // 获取当前线程
    Thread t = Thread.currentThread();
    
    ThreadLocalMap map = getMap(t);
    if (map != null) {
    	// 从ThreadLocalMap中获取K-V Entry节点
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            // 获取存储的value副本值,并且返回
            T result = (T)e.value;
            return result;
        }
    }
    // ThreadLocal类返回的是null,其他子类实现的是对应的hashCode
    // 如果找不到map,会初始化ThreadLocalMap,并把当前ThreadLocal和initialValue()副本值放入
    return setInitialValue();
}

/** 保存当前线程的副本变量值 */
public void set(T value) {
    Thread t = Thread.currentThread();
    // 获取当前线程的map
    ThreadLocalMap map = getMap(t);
    if (map != null)
        // 如果不为null。则修改当前线程的副本
        map.set(this, value);
    else
        // 如果map为null 就会初始化ThreadLocalMap,并把当前ThreadLocal和副本value放入map
        createMap(t, value);
}

/** 溢出当前线程的副本变量值 */
public void remove() {
    ThreadLocalMap m = getMap(Thread.currentThread());
    if (m != null)
        m.remove(this);
}

五、总结

ThreadLocal是一个本地线程副本变量工具类,主要用于将私有线程和该私有线程存放的副本对象做一个映射,各个线程之间的变量互不干扰,在高并发场景下,可实现无状态调用,特别适合于各个线程依赖不通的变量值完成操作场景

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值