ThreadLocal
JDK
基于JDK1.8
ThreadLocal的使用场景
在有些业务场景中,我们希望每个线程(Thread)能够维护一份自己的变量副本,这个变量的值不受其他线程的影响,这个时候我们就可以使用ThreadLocal。
应用ThreadLocal的场景主要包括:
- 当作请求的上下文:比如在业务逻辑中,我们可能有很多地方都要获取用户的请求IP地址,这个时候,我们就可以在Filter一开始的时候将IP解析出来并放到ThreadLocal中,通常我们会创建一个类,比如叫IPContext,在这个IPContext中持有一个ThreadLocal,然后把解析出来的IP放到这个ThreadLocal中,使用的时候只要从IPContext中的ThreadLocal获取就可以了。
- 复杂业务逻辑的参数传递:比如如果我们想从程序的任一位置获取HttpServletRequest,那么就可以使用SpringMVC中的RequestContextHolder,另外比如在业务逻辑处理中,我们想获得操作的用户,我们就可以把用户放到一个自定义的Context中,然后从Context中获取,这样就比在每个方法中传来传去要方便的多。
使用ThreadLocal要注意的一点就是由于线程复用(使用了线程池的时候)要记得使用完之后要将ThreadLocal进行remove(),清除数据,否则当这个线程再次被复用的时候,可能会获取到上一次设置在里面的东西。比如我们在Filter进入的时候对ThreadLocal进行赋值,那么要在Filter执行之后将付给ThreadLocal的值清除。
ThreadLocal是线程安全的么
ThreadLocal是线程安全的,并且ThreadLocal不会被其他线程访问到,确切的说ThreadLocal是线程隔离的。为什么呢?
如果我们查看Thread.java的源代码,就会发现Thread类中持有了一个ThreadLocalMap对象,我们现在可以把ThreadLocalMap简单的认为是一个key、value的表,key的类型是ThreadLocal对象(其实是ThreadLocal对象的弱引用),value就是我们想存储的值。因为ThreadLocalMap是不能被其他线程访问的,所以里面存储的内容自然也就是线程安全的。
虽然这种结构保证了线程安全,但是,你可千万不要把存储的值弄成线程共享的。比如你要存储一个User对象,而这个User对象又是可以在任何线程中访问和设置的。比如下面的例子中list就是线程共享的。
private static List<String> list = new ArrayList<String>(); static ThreadLocal<List> context = new ThreadLocal<List>(); public static void main(String[] args) throws InterruptedException { context.set(list); new Thread(new Runnable() { public void run() { context.set(list); context.get().add("hello"); } }).start(); TimeUnit.SECONDS.sleep(1); //结果是1 System.out.println(context.get().size()); }
|
对ThreadLocal的操作其实是对Thread中的ThreadLocalMap操作
ThreadLocal对象本身并不存储我们认为放到ThreadLocal中的值,我们通过ThreadLocal对象操作get、set和remvoe时,其实是对ThreadLocalMap的操作。ThreadLocal对象(其实是这个对象的弱引用)只是这个Map中的一个key,这个Map中对应的Value才是我们使用ThreadLocal设置的值。举个例子,我们使用set操作设置值的时候,我们看下源代码:
public void set(T value) { //获取当前线程 //获取当前线程的ThreadLocalMap,getMap方法就是return t.threadLocals; ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
|
换句话说:在实际的使用中ThreadLocal对象本身并不是每个线程一份的,但是通过ThreadLocal对象进行get、set和remove操作的内容却是每个线程单独占有的。因为它操作的是每个线程中ThreadLocalMap中的内容,ThreadLocal对象仅仅是去寻找Map中值一个key。不同的线程中这个key可能是相同的,但是通过这个key找到的内容却是每个线程独有的。
ThreadLocal就这么多内容
其实ThreadLocal本身并不复杂,复杂的是ThreadLocalMap的实现。Java很好的对TheadLcoalMap的操作进行了封装,使我们不用关心复杂的逻辑实现,对于ThreadLocal的理解以上这么多就可以了。下面我们开始讲解ThreadLocalMap。
ThreadLocalMap
ThreadLocalMap是Thread持有的对象
ThreadLocalMap这个类是定义在ThreadLocal里的,是ThreadLocal的内部类,但是却是被Thread持有的。
/* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null; |
ThreadLocalMap的几个属性
/** * 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. */ 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
|
INITIAL_VALUE:常量,16,最一开始初始化ThreadLocalMap的表的大小。是2的幂。
table:类型为Entry的数组,(Entry是ThreadLocalMap的一个内部类)实际存储内容的地方,这个数组的大小必须是2的幂。
size:table中实际存储的元素的个数,注意不是table.length。
threshold:阈值,根据这个阈值来调整表的大小。后面会详细讲。
Entry的结构
/** * The entries in this hash map extend WeakReference, using * its main ref field as the key (which is always a * ThreadLocal object). Note that null keys (i.e. entry.get() * == null) mean that the key is no longer referenced, so the * entry can be expunged from table. Such entries are referred to * as "stale entries" in the code that follows. */ static class Entry extends WeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } }
|
Entry继承弱引用,Entry的key永远都是ThreadLocal对象的弱引用。空的key比如entry.get() == null表示这个key不再被引用了,那么这个entry就可以从table中删除了。
什么是弱引用?
弱引用的官方定义:
弱引用对象的存在不会阻止它所指向的对象被垃圾回收器回收。弱引用最常见的用途是实现规范映射(canonicalizing mappings,比如哈希表)。假设垃圾收集器在某个时间点决定一个对象是弱可达的(weakly reachable)(也就是说当前指向它的全都是弱引用),这时垃圾收集器会清除所有指向该对象的弱引用,然后把这个弱可达对象标记为可终结(finalizable)的,这样它随后就会被回收。与此同时或稍后,垃圾收集器会把那些刚清除的弱引用放入创建弱引用对象时所指定的引用队列(Reference Queue)中。 |
简单的说,弱引用只是一个引用,它需要引用一个对象,这种引用并不会影响引用对象的垃圾回收,当引用对象被垃圾回收了,那么这个对象的弱引用也会被垃圾回收。另外我们可以用过下面的例子更直观的看下弱引用的垃圾回收
public static WeakReference<String> wr; public static void main(String[] args) { initWeakReference(); p("主方法:" + wr.get()); System.gc(); p("主方法刚进行GC:" + wr.get()); } private static void initWeakReference() { String s = new String("hello"); wr = new WeakReference<String>(s); p("子方法中刚初始化:" + wr.get()); System.gc(); p("子方法中刚进行完GC:" + wr.get()); } private static void p(Object o){ System.out.println(o); }
|
输出结果如下:
子方法中刚初始化:hello
子方法中刚进行完GC:hello
主方法:hello
主方法刚进行GC:null
Entry为什么要用ThreadLocal的弱引用
如果不使用弱引用的化,我们在一个线程里new了很多个ThreadLocal并设置了一些内容,如果线程本身不回收,那么设置的这些内容就不会被回收,及时new的ThreadLocal对象看起来已经超过生命周期了,比如在方法里new的ThreadLocal,已经退出了方法,看样子这个ThreadLocal对象应该被销毁了,其实没有。因为这些对象是放到了线程的ThreadLocalMap里,线程没有销毁,ThreadLocalMap及里面的内容就会一直保留。
如果使用了弱引用则就没有这种问题,ThreadLocal对象本身的生命周期并不会收到ThreadLocalMap的影响。TheadLocalMap的get和set方法(也就是当我们操作ThreadLocal对象get和set操作的时候),也对通过弱引用获取到的对象为null的情况进行了处理(我们稍后会说到),保证了这个Map不会无限制的增长,导致内存泄漏。
在现实的应用中,其实这种情况是及其不容易发生的。通常我们都将ThreadLocal作为上下文使用,也不会一直new。在现实使用中要注意的就是线程复用问题,并且ThreadLocal中的内容不会被其他线程或子线程获取到。如果我们的程序中涉及到子线程要从ThreadLocal的上下文中取值,就要注意了,不能使用它。有些框架本身也会使用子线程,这种就比较难以发现了,比如Hystrix。
ThreadLocalMap如何实现Hash
ThreadLocalMap使用Entry[]进行数据存储。当我们通过ThreadLocal存入或获取内容时是如何操作的呢?
我们就拿第一次创建ThreadLocalMap来举例。不论是获取还是设置当线程中还没有ThreadLocalMap的时候就创建一个ThreadLocalMap,并放入第一个值,如果是get操作则放入的值是null。
void createMap(Thread t, T firstValue) { /**这里的this,就是ThreadLocal对象本身 */ t.threadLocals = new ThreadLocalMap(this, firstValue); } ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) { /** 初始化一个大小length为16的数组 */ table = new Entry[INITIAL_CAPACITY]; /** 这一步其实就是一步取模操作,使用ThreadLocal的threadLocalHashCode属性进行取模*/ int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1); /** 取的模值就作为数组的角标*/ table[i] = new Entry(firstKey, firstValue); /** 记录下我们已经存了一个元素Entry了 */ size = 1; /** 设置一下阈值 */ setThreshold(INITIAL_CAPACITY); }
|
使用位操作进行取模
我们可以使用位操作&进行取模,这样做的好处就是快,因为位运算要比直接进行取模%操作要快的多。但是有个要求就是被取模的数必须是2的幂。
即:a%b = a&(b-1),前提b是2的幂。
我们可以看下面的例子:
System.out.println(0 % 8 + " " + (0 & (8 - 1))); System.out.println(3 % 8 + " " + (3 & (8 - 1))); System.out.println(8 % 8 + " " + (8 & (8 - 1))); System.out.println(10 % 8 + " " + (10 & (8 - 1))); System.out.println(16 % 8 + " " + (16 & (8 - 1)));
|
结果:
0 0
3 3
0 0
2 2
0 0
为什么能用位操作代替取模运算呢?首先我们要知道位移操作,也就是>>
比如16÷8=2
我们换成二进制就是10000 ÷1000 = 10 相当于从10000到10右移了3位,也就是10000(二进制)>>3
再比如19÷8=2余3
我们换成二进制就是10011÷10000 = 10余011 也就是从10011到10右移了3位,移出去的011就是余数,也就是十进制的3。
那么换句话说如果除数是2的幂的化,比如2n,那么余数就是移出去的n位二进制数。
关键点来了,位&操作,有个特点就是只有1和1的位操作是1,其他都是0。
2n-1就刚好是n位个1。比如7(23-1)的二进制就是111。当我们对111进行位运算时,比如a对111进行位运算:
如果a大于3位,那么大于3位的部分(左侧的部分)完全可以忽略,因为111左侧的部分都是0,所以左侧超过3位的地方位运算的结果都是0,最终的结果就是a的最右的3位;如果a小于等于3位,那么位运算的结果就是a本身,也是a的最右侧的3位。
通过前面的介绍,我们知道了如果某个数对2n取余,余数就是最右侧的n位二进制数,而这最右侧的n位二进制数,就刚好可以通过对2n-1进行位运算而得来。
如何使用数组来实现Hash
当我们使用ThreadLocal对象进行get或set操作时,先从ThreadLocal获取threadLocalHash属性,这是一个int数,然后再根据数组的length进行取模,从而获得角标,就能获取到这个ThreadLocal对象对应的值了。从而完成了Hash。
我们看下当我们new了多个ThreadLocal对象时,是如何放入数组的。我把里面一些核心的代码提出了出来并进行了测试:
private static final int HASH_INCREMENT = 0x61c88647; private static final int INITIAL_CAPACITY = 16; private static AtomicInteger nextHashCode = new AtomicInteger(); public static void main(String[] args){ //获取16次角标,模拟创建了16个ThreadLcoal对象 for(int i = 0; i < INITIAL_CAPACITY; i++){ System.out.println(getIndex()); } } private static int nextHashCode() { int hashCode = nextHashCode.getAndAdd(HASH_INCREMENT); System.out.print(String.format("hashCode: %s \t 0x%x \t index: " , hashCode, hashCode)); return hashCode; } private static int getIndex(){ return nextHashCode() & (INITIAL_CAPACITY - 1); }
|
结果:
hashCode: 0 0x0 index: 0
hashCode: 1640531527 0x61c88647 index: 7
hashCode: -1013904242 0xc3910c8e index: 14
hashCode: 626627285 0x255992d5 index: 5
hashCode: -2027808484 0x8722191c index: 12
hashCode: -387276957 0xe8ea9f63 index: 3
hashCode: 1253254570 0x4ab325aa index: 10
hashCode: -1401181199 0xac7babf1 index: 1
hashCode: 239350328 0xe443238 index: 8
hashCode: 1879881855 0x700cb87f index: 15
hashCode: -774553914 0xd1d53ec6 index: 6
hashCode: 865977613 0x339dc50d index: 13
hashCode: -1788458156 0x95664b54 index: 4
hashCode: -147926629 0xf72ed19b index: 11
hashCode: 1492604898 0x58f757e2 index: 2
hashCode: -1161830871 0xbabfde29 index: 9
我们能够看到如果创建16个ThreadLocal对象的化,会全部放到长度只有16的数组中。
这里面最关键的就是这个数字:0x61c88647
这个数叫斐波那契散列的乘数。斐波那契数列和黄金分隔比例有非常紧密的关系,我们看看这个数字是怎么得到的。
//0.6180339887是黄金分割比,对于32位数的这个黄金分隔点的值就是下面的样子 //也就是斐波那契散列对于32位数的乘数,也就是所说的golden number Long a = (long) (0.6180339887 * (1L<<32)); //这个乘数也可以使用下面这个公式计算出来,b和a的结果是一样的 Long b = (long) ((1L << 31) * (Math.sqrt(5) - 1)); System.out.println(a); System.out.println(b); //这个乘数要大于int的范围所以从long转到int的数是负的,下面有两种方式,得到的结果也都是一样的 //0X61c88647这个数就是这么算出来的 System.out.println(a.intValue() + " " + String.format("0x%x", -a.intValue())); System.out.println(b.intValue() + " " + String.format("0x%x", new Long((1L << 32) - b).intValue()));
|
结果:
2654435769
2654435769
-1640531527 0x61c88647
-1640531527 0x61c88647
ThreadLocal的逻辑是这样的,有个线程安全的全局静态变量nextHashCode,最一开始这个变量的值是0,每new一个ThreadLocal对象,就将对象的threadLocalHashCode属性设置为nextHashCode变量,然后把这个变量增加0x61c88647。
这样做神奇的是threadLocalHashCode属性算出来的数组角标非常分散并且正好填充好数组。
防止内存泄漏
前面我们讲到了Entry中的key其实是ThreadLocal对象的弱引用。当我们使用key去get实际的ThreadLocal对象时,如果得到的null,则说明ThreadLocal对象被垃圾回收了。这样的Entry其实已经每什么用了,ThreadLocalMap则要把这些Entry对象从Entry[]中清理掉,我们看看是怎么清理的。
ThreadLocalMap在进行get和set的时候都会进行失效元素的检查和删除。
清除失效元素的逻辑参考:expungeStaleEntry方法。这个方法比较有特点,它会删除给定数组下标的数据,然后继续向下查找把找到的其他失效元素也删除掉,直到遇到null为止。
如何扩容
在进行set的时候,如果发现元素的数量大于负载因子(阈值,是数组长度的2/3),会先把数组中所有元素过滤一遍,移除失效的元素,在这之后如果发现元素的数量仍大于数组长度的1/2(size >= threshold - threshold / 4,因为threshold是数组长度的2/3,所以这里就是数组长度的1/2)才会进行翻倍扩容。翻倍扩容的时候会重新计算每个元素的新的数组下标,并放入新的数组中。
为何会有hash碰撞
当我们把过多的数据放入有限的数组中时,会使用哈希函数计算要放入数据的数组下标,如果这个位置之前放入了元素,也就是之前也有个元素计算的数组下标也是这个的时候那么就产生了hash碰撞。同理如果查询的时候,发现从通过哈希函数得到的数组下标所取得的元素的key不是当前要取的数据时,也会产生hash碰撞。
为了提高hash表的查询速率,当元素数量大于一定的值(负载因子)的时候,就会进行扩容,从而减少hash碰撞。
ThreadLocalHashMap的哈希函数是基于一个自增长的AtomicInteger,每次增长0x61c88647,得到的值我们称之为hashCode,通过这个hashCode计算得到的数据下标分散非常均匀,也就是说产生hash碰撞的概率非常小,那么有多小呢?
我用电脑算了一下,直到产生内存溢出,也没算出当数组为多大的时候,也会产生hash碰撞,所以我们几乎可以认为是不可能发生的。
private static AtomicInteger nextHashCode = new AtomicInteger(); private static final int HASH_INCREMENT = 0x61c88647; private static int INITIAL_CAPACITY = 8; public static void main(String[] args){ Set<Integer> set = new HashSet<Integer>(); do { set.clear(); INITIAL_CAPACITY = INITIAL_CAPACITY * 2; for (int i = 0; i < INITIAL_CAPACITY; i++) { //System.out.println(getIndex()); set.add(getIndex()); } System.out.println(set.size()); }while (set.size() == INITIAL_CAPACITY); } private static int nextHashCode() { int hashCode = nextHashCode.getAndAdd(HASH_INCREMENT); return hashCode; } private static int getIndex(){ return nextHashCode() & (INITIAL_CAPACITY - 1); }
运算结果:
524288
1048576
2097152
4194304
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
如果解决hash碰撞
解决hash碰撞的方法有很多,ThreadLocalMap采用的是线性探测(linear-probe)。
线性探测就是如果发现该位置有碰撞就继续向下寻找,一直到遇到null为止。
总体而言
总体而言,ThreadLocalMap设计有几大特色:
- 使用了ThreadLocal对象的弱引用作为key来避免内存泄漏
- 在get和set的时候都进行了失效元素(stale entry)的清理,也在进行避免内存泄漏。
- 在hash函数中使用了斐波那契数列的乘数,从而使数据分布非常均匀,减少了hash碰撞
其中有一点我是没有想清楚的,即使不使用斐波那契数列的乘数,我就是把hashCode一个数一个数的加,也不会产生hash碰撞。
因为ThreadLocalMap和普通的HashMap是不一样的,普通的HashMap的hashCode取决于要存入的数据的key,因为用户可能存入各种各样的key所以比较随机,而ThreadLocalMap的key是自维护的,每次生成ThreadLocal的时候这个hashCode就生成好了,再加上我们有扩容机制,是不论怎样都是不会出现hash碰撞的。
源码解析
import java.lang.ref.*;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
/**
* This class provides thread-local variables. These variables differ from
* their normal counterparts in that each thread that accesses one (via its
* {@code get} or {@code set} method) has its own, independently initialized
* copy of the variable. {@code ThreadLocal} instances are typically private
* static fields in classes that wish to associate state with a thread (e.g.,
* a user ID or Transaction ID).
*
* <p>For example, the class below generates unique identifiers local to each
* thread.
* A thread's id is assigned the first time it invokes {@code ThreadId.get()}
* and remains unchanged on subsequent calls.
* <pre>
* import java.util.concurrent.atomic.AtomicInteger;
*
* public class ThreadId {
* // Atomic integer containing the next thread ID to be assigned
* private static final AtomicInteger nextId = new AtomicInteger(0);
*
* // Thread local variable containing each thread's ID
* private static final ThreadLocal<Integer> threadId =
* new ThreadLocal<Integer>() {
* @Override protected Integer initialValue() {
* return nextId.getAndIncrement();
* }
* };
*
* // Returns the current thread's unique ID, assigning it if necessary
* public static int get() {
* return threadId.get();
* }
* }
* </pre>
* <p>Each thread holds an implicit reference to its copy of a thread-local
* variable as long as the thread is alive and the {@code ThreadLocal}
* instance is accessible; after a thread goes away, all of its copies of
* thread-local instances are subject to garbage collection (unless other
* references to these copies exist).
*
* @author Josh Bloch and Doug Lea
* @since 1.2
*/
public class ThreadLocal<T> {
/**
* ThreadLocals rely on per-thread linear-probe hash maps attached
* to each thread (Thread.threadLocals and
* inheritableThreadLocals). The ThreadLocal objects act as keys,
* searched via threadLocalHashCode. This is a custom hash code
* (useful only within ThreadLocalMaps) that eliminates collisions
* in the common case where consecutively constructed ThreadLocals
* are used by the same threads, while remaining well-behaved in
* less common cases.
*/
private final int threadLocalHashCode = nextHashCode();
/**
* The next hash code to be given out. Updated atomically. Starts at
* zero.
*/
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;
/**
* Returns the next hash code.
*/
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
/**
* Returns the current thread's "initial value" for this
* thread-local variable. This method will be invoked the first
* time a thread accesses the variable with the {@link #get}
* method, unless the thread previously invoked the {@link #set}
* method, in which case the {@code initialValue} method will not
* be invoked for the thread. Normally, this method is invoked at
* most once per thread, but it may be invoked again in case of
* subsequent invocations of {@link #remove} followed by {@link #get}.
*
* <p>This implementation simply returns {@code null}; if the
* programmer desires thread-local variables to have an initial
* value other than {@code null}, {@code ThreadLocal} must be
* subclassed, and this method overridden. Typically, an
* anonymous inner class will be used.
*
* @return the initial value for this thread-local
*/
protected T initialValue() {
return null;
}
/**
* Creates a thread local variable. The initial value of the variable is
* determined by invoking the {@code get} method on the {@code Supplier}.
*
* @param <S> the type of the thread local's value
* @param supplier the supplier to be used to determine the initial value
* @return a new thread local variable
* @throws NullPointerException if the specified supplier is null
* @since 1.8
*/
public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
return new SuppliedThreadLocal<>(supplier);
}
/**
* Creates a thread local variable.
* @see #withInitial(java.util.function.Supplier)
*/
public ThreadLocal() {
}
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
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;
}
}
//如果ThreadLocalMap还没有(第一次用)就初始化一个,并在ThreadLocalMap放入一个空元素
return setInitialValue();
}
/**
* Variant of set() to establish initialValue. Used instead
* of set() in case user has overridden the set() method.
*
* @return the initial value
*/
private T setInitialValue() {
T value = initialValue();//return null,我们可以写个ThreadLocal的子类复写这个方法这样返回的就是我们自定义的了,目前看没什么场景
Thread t = Thread.currentThread();
//返回线程t的ThreadLocalMap
ThreadLocalMap map = getMap(t);//return t.threadLocals;
if (map != null)
map.set(this, value);
else
//如果还没有就创建一个,并放入一个元素,元素的值是value,也就是null
createMap(t, value);//t.threadLocals = new ThreadLocalMap(this, firstValue);
return value;
}
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
/**
* Removes the current thread's value for this thread-local
* variable. If this thread-local variable is subsequently
* {@linkplain #get read} by the current thread, its value will be
* reinitialized by invoking its {@link #initialValue} method,
* unless its value is {@linkplain #set set} by the current thread
* in the interim. This may result in multiple invocations of the
* {@code initialValue} method in the current thread.
*
* @since 1.5
*/
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
/**
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
/**
* Factory method to create map of inherited thread locals.
* Designed to be called only from Thread constructor.
*
* @param parentMap the map associated with parent thread
* @return a map containing the parent's inheritable bindings
*/
static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
return new ThreadLocalMap(parentMap);
}
/**
* Method childValue is visibly defined in subclass
* InheritableThreadLocal, but is internally defined here for the
* sake of providing createInheritedMap factory method without
* needing to subclass the map class in InheritableThreadLocal.
* This technique is preferable to the alternative of embedding
* instanceof tests in methods.
*/
T childValue(T parentValue) {
throw new UnsupportedOperationException();
}
/**
* An extension of ThreadLocal that obtains its initial value from
* the specified {@code Supplier}.
*/
static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {
private final Supplier<? extends T> supplier;
SuppliedThreadLocal(Supplier<? extends T> supplier) {
this.supplier = Objects.requireNonNull(supplier);
}
@Override
protected T initialValue() {
return supplier.get();
}
}
/**
* ThreadLocalMap is a customized hash map suitable only for
* maintaining thread local values. No operations are exported
* outside of the ThreadLocal class. The class is package private to
* allow declaration of fields in class Thread. To help deal with
* very large and long-lived usages, the hash table entries use
* WeakReferences for keys. However, since reference queues are not
* used, stale entries are guaranteed to be removed only when
* the table starts running out of space.
*/
static class ThreadLocalMap {
/**
* The entries in this hash map extend WeakReference, using
* its main ref field as the key (which is always a
* ThreadLocal object). Note that null keys (i.e. entry.get()
* == null) mean that the key is no longer referenced, so the
* entry can be expunged from table. Such entries are referred to
* as "stale entries" in the code that follows.
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
//这里能够看到元素的key是ThreadLocal对象的弱引用
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* The initial capacity -- MUST be a power of two.
*/
//初始的数组长度为16
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*/
//数组
private Entry[] table;
/**
* The number of entries in the table.
*/
//实际存储的元素的数量
private int size = 0;
/**
* The next size value at which to resize.
*/
//阈值,负载因子,是数组长度的2/3,当元素数量大于阈值时进行扩容操作,
// 但是在扩容之前会把数组中的失效元素全部清理一遍,如果清理之后,元素的数量大于数组长度的1/2,才会真正进行翻倍扩容
private int threshold; // Default to 0
/**
* Set the resize threshold to maintain at worst a 2/3 load factor.
*/
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
/**
* Increment i modulo len.
*/
//返回下一个数组下标,其实这是一个循环,如果找到最后又会从头返回
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
/**
* Decrement i modulo len.
*/
//返回上一个数组下标,其实这是一个循环,如果找到最后又会从尾返回
private static int prevIndex(int i, int len) {
return ((i - 1 >= 0) ? i - 1 : len - 1);
}
/**
* 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) {
//初始化一个16长度的数组
table = new Entry[INITIAL_CAPACITY];
//算个数组的下标,这个计算的方法就叫哈希函数
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
//在数据中放入一个元素
table[i] = new Entry(firstKey, firstValue);
//元素计数器设置为1,因为目前只有一个
size = 1;
//根据容量大小设置一个阈值
setThreshold(INITIAL_CAPACITY);//threshold = len * 2 / 3;
}
/**
* Construct a new map including all Inheritable ThreadLocals
* from given parent map. Called only by createInheritedMap.
*
* @param parentMap the map associated with parent thread.
*/
private ThreadLocalMap(ThreadLocalMap parentMap) {
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)
h = nextIndex(h, len);
table[h] = c;
size++;
}
}
}
}
/**
* Get the entry associated with key. This method
* itself handles only the fast path: a direct hit of existing
* key. It otherwise relays to getEntryAfterMiss. This is
* designed to maximize performance for direct hits, in part
* by making this method readily inlinable.
*
* @param key the thread local object
* @return the entry associated with key, or null if no such
*/
private Entry getEntry(ThreadLocal<?> key) {
//算一下数组的下标
int i = key.threadLocalHashCode & (table.length - 1);
//从数组中获取元素
Entry e = table[i];
//如果拿到了元素,并且元素的key就是传入的ThreadLocalduix的化就返回
//这里e.get() != key的情况有两种,一种是e.get()是null,另一种是有hash碰撞,这个槽位被别人占用了,需要继续探测
if (e != null && e.get() == key)
return e;
else
//1、如果e是null,表示这个东东就没有
// 2、如果e.get()是null或者有hash碰撞则进入getEntryAfterMiss方法
return getEntryAfterMiss(key, i, e);
}
/**
* Version of getEntry method for use when key is not found in
* its direct hash slot.
*
* @param key the thread local object
* @param i the table index for key's hash code
* @param e the entry at table[i]
* @return the entry associated with key, or null if no such
*/
private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
Entry[] tab = table;
int len = tab.length;
//如果e不是null,说明有hash碰撞,进行线程探测
//线性探测就是一直找,一直找到一个null为止,具体的可以去看看数据结构了
while (e != null) {
ThreadLocal<?> k = e.get();
//如果元素的key就是参数中的ThreadLocal对象,说明通过线性探测找到了,找到了就返回就可以了
if (k == key)
return e;
//如果key==null,注意此时e不是null,说明ThreadLocal对象被垃圾回收了,弱引用返回了null
//则要调用expungeStaleEntry去处理掉已经失效的数据
if (k == null)
expungeStaleEntry(i);
else
//如果不是上面的情况,下标加1继续找
i = nextIndex(i, len);//return ((i + 1 < len) ? i + 1 : 0) 如果找到数组末尾就再从头开始找,也是线性探测的规则
//获取到下一个元素,然后进入下一次循环
e = tab[i];
}
//如果e本身就null,就直接返回null了
return null;
}
/**
* Set the value associated with key.
*
* @param key the thread local object
* @param value the value to be 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);
//因为可能会发生hash碰撞,我们要找到一个null的位置放进去(线性探测法)
//这个循环是在找不为空的位置,如果不为空就会进行for内部,空的位置在for结束的后面
//如果在这个循环里面找到了,说明要设置的元素之前就存在了,这次只是修改一下
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
//如果我们在不为空的位置 找到了要存入的key,说明这个key,已经存在,把值重新设置一下就返回了
if (k == key) {
e.value = value;
return;
}
//如果k==null说明弱引用的ThreadLocal对象被垃圾回收了,要进行一下清理,防止内存泄漏
//这个时候可能有两种情况,一种情况是如果要设置的元素之前没设置过,那么就刚好可以放到这个位置
//第二种情况是,如果要设置的元素之前已经设置过了,这次只是修改的化,我们就不能放到这个位置
//因为在这个if里直接就return了,所以我们肯定是要在replaceStaleEntry这个方法里进行设置值的
if (k == null) {
replaceStaleEntry(key, value, i);
//这里是return说明,说明在replaceStaleEntry这个方法里完成了set设置,然后就直接结束了
return;
}
}
//说明之前没有这个key,设置的是一个新的元素
//找到空的位置,将元素放入
tab[i] = new Entry(key, value);
//元素计数器加1
int sz = ++size;
//扫描了一下,如果发现没有失效的元素需要清理并且元素数量大于数组的2/3,那么就要进行扩容了
if (!cleanSomeSlots(i, sz) && sz >= threshold)
//扩容
rehash();
}
/**
* Remove the entry for key.
*/
private void remove(ThreadLocal<?> key) {
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
//从i位置一直向下找,一直到找到该元素为止(hash冲突情况)
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
//找到了就进行清除
if (e.get() == key) {
//把这个元素失效
e.clear();//this.referent = null;
//这步进行真正的清除
expungeStaleEntry(i);
return;
}
}
}
/**
* Replace a stale entry encountered during a set operation
* with an entry for the specified key. The value passed in
* the value parameter is stored in the entry, whether or not
* an entry already exists for the specified key.
*
* As a side effect, this method expunges all stale entries in the
* "run" containing the stale entry. (A run is a sequence of entries
* between two null slots.)
*
* @param key the key
* @param value the value to be associated with key
* @param staleSlot index of the first stale entry encountered while
* searching for key.
*/
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).
//slotToExpunge这个变量很有趣,这个变量的值在这个方法的过程中永远是第一个需要清除的失效元素的位置
//如果我们看下面的逻辑,会发现我们会从入参staleSlot(失效元素的位置)的位置向上和向下去寻找其他失效的元素
//我们可能会在向上寻找和向下寻找的过程中遇到很多需要清除的失效元素,但是slotToExpunge始终指向第一个失效元素的位置
//因为调用expungeStaleEntry方法时,会一连串的清除所有的失效元素,直到遇到null为止。
int slotToExpunge = staleSlot;
//从失效元素下标向上寻找,一直到遇到null的位置为止
for (int i = prevIndex(staleSlot, len);//((i - 1 >= 0) ? i - 1 : len - 1)寻找上一个位置,如果找到头就从尾部再往找
(e = tab[i]) != null;
i = prevIndex(i, len))
//因为过程中可能遇到多个需要清理的失效元素,最终slotToExpunge只记录第一个(从上到下)需要清理的失效元素的为止
if (e.get() == null)
slotToExpunge = i;
// Find either the key or trailing null slot of run, whichever
// occurs first
//从失效的元素下标的下一个向下寻找,一直到遇到null为止
//向下寻找的目的是什么呢?一个是向下寻找时,我们可能会遇到要设置的key,如果遇到了就进行下设置
//如果没有遇到,并且在之前向上寻找时也没有遇到失效的元素,我们就给slotToExpunge设置一个要清除的位置
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) {
//这块的逻辑是什么意思呢
//我们要从调用这个方法的set说起
//当要设置一个值的时候,发现要设置的位置失效了(弱引用的对象被垃圾回收了),然后我们进入了这个方法
//在这个方法里,我们就从这个位置向下找(当然遇到null就不找了),发现找到了,说明之前设置过这个key
//我们就把失效的位置的元素和要设置位置的元素进行了一下调换,然后再把失效的位置进行清除
//问题是我们要进行调换位置呢?
//其实不调换也行的,不调换并不会影响失效位置的删除以及如果前面在向上查抄时遇到的失效元素的删除
//这里调换的好处是什么呢?如果前面向上查找没有找到失效元素的化会节省几次查找,另一个是将这个元素提前了可能提升后续查询的速度
//但是这种好处,我觉得优点微弱
e.value = value;
tab[i] = tab[staleSlot];
tab[staleSlot] = e;
// Start expunge at preceding stale entry if it exists
//slotToExpunge == staleSlot说明之前向上找失效元素的时候没有找到,所以slotToExpunge还是等于staleSlot的
//因为刚才已经进行了交换,staleSlot位置已经不是失效元素了,i位置变成了失效元素的位置
//slotToExpunge = i 让slotToExpunge永远都代表要删除的位置
if (slotToExpunge == staleSlot)
slotToExpunge = i;//slotToExpunge重新设置为失效的位置
//expungeStaleEntry做下清除,再cleanSomeSlots做下扫描清除一下
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
//staleSlot是方法进来时传递的失效元素的数组下标,上面已经做了一次线性探测
//探测过程中没有发现相同的key,也就是没有发现hash冲突
//所以这里就直接把这个失效的数组位置设置为要进行set的元素就可以了
tab[staleSlot].value = null;
tab[staleSlot] = new Entry(key, value);
// If there are any other stale entries in run, expunge them
//当slotToExpunge != staleSlot时,说明除了staleSlot位置外还有slotToExpunge位置也是失效的位置
//我们要进行一下清除
if (slotToExpunge != staleSlot)
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
/**
* 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).
*/
//清除staleSlot位置的元素,清除完之后继续向下寻找清除失效元素,直到遇到null为止
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// 这个方法进来的时候说明弱引用的对象已经被垃圾回收了
// 这这个元素就没什么用了,进行一下清理,防止长时间不清理内存溢出
tab[staleSlot].value = null;//将元素设置为null,清理下空间
tab[staleSlot] = null;//将数组的位置空出来,便于放置其他的元素
//元素少了一个,元素计数器减1
size--;
// Rehash until we encounter null
Entry e;
int i;
//其实上面的清理工作已经完成了,这里额外做了一些事,就是把其他可能需要清理的元素也清理一下
//因为上面只是针对指定的元素的进行了清理,其他的元素如果也失效了,但是一直未被访问,则不会被清理,所以这里进行清理一下也是有必要的
//但是这里也没有把整个数组全部扫描,一直扫描到null的元素就结束了
for (i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
//如果k==null说明弱引用引用的对象被垃圾回收了,这里清理下元素
if (k == null) {
e.value = null;
tab[i] = null;
//元素计数器减一
size--;
} else {
//其实上面的清理逻辑就结束了,下面是重新hash
//为什么要重新hash,因为经过清理之后,数组中释放出了一些空的位置,
// 如果之前这个位置有hash碰撞,元素放到其他位置的元素,我们这次就要把这些元素调整到这个位置,否则这个元素就找不到了
//比如说i位置被清空了,如果i+1位置之前是由于hash碰撞被放置的元素,则我们要把i+i位置的元素放到i上,
// 因为后面i+2、i+3也有可能是这种情况,所以我们要循环处理,直到碰到一个null位置为止
//计算一下k元素的数组下标h(记住k元素是通过下标i取出来的)
int h = k.threadLocalHashCode & (len - 1);
//如果计算得到的下标和当前下标不一样,说明k元素本应该放在h位置,但是由于hash碰撞被放到了i位置
if (h != i) {
//我们先将i位置清空,因为k元素本来也不应该在i位置的,下面我们给k元素重新选个位置
tab[i] = null;
//k元素本应该在h位置,如果h位置是null是化我们就直接设置一下就好了,即tab[h] = e;
//如果h位置被占了,我们就向下继续找,一直找到一个null的位置将k放入
//这里我们举一个整体的例子:
//比如我们发现某个位置的弱引用失效了,我们就将这个位置清空,因为可能存在hash碰撞的可能,
// 所以我们要看看这个位置后面的一个位置有没有值,如果没有值说明没有hash碰撞,就结束了
//如果有值,我们要看看这个值是不是一个hash碰撞的元素,也就是上面的(h != i)判断,如果不是也就结束了
//如果是,我们就放到刚才清了的那个地方就行了,因为有可能有多个hash碰撞的元素,所以我们不能就这样直接放
//从而有了while (tab[h] != null)这种操作,保证所有hash碰撞的元素都被重新放了一遍
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
//返回下一个空的位置的数组下标
return i;
}
/**
* Heuristically scan some cells looking for stale entries.
* This is invoked when either a new element is added, or
* another stale one has been expunged. It performs a
* logarithmic number of scans, as a balance between no
* scanning (fast but retains garbage) and a number of scans
* proportional to number of elements, that would find all
* garbage but would cause some insertions to take O(n) time.
*
* @param i a position known NOT to hold a stale entry. The
* scan starts at the element after i.
*
* @param n scan control: {@code log2(n)} cells are scanned,
* unless a stale entry is found, in which case
* {@code log2(table.length)-1} additional cells are scanned.
* When called from insertions, this parameter is the number
* of elements, but when from replaceStaleEntry, it is the
* table length. (Note: all this could be changed to be either
* more or less aggressive by weighting n instead of just
* using straight log n. But this version is simple, fast, and
* seems to work well.)
*
* @return true if any stale entries have been removed.
*/
private boolean cleanSomeSlots(int i, int n) {
//其实这个方法可以算是一个锦上添花的功能,目的也是清理失效的元素
//这个方法只会在set的时候调用,get的时候是不调用的(应该是出于性能考虑)
//这个方法的过程是这样的:
//弄一个循环,循环的次数取决于过程中有没有遇到需要清理的失效元素
//1、如果没有遇到,那么就循环入参n(数组长度或元素数量,取决于调用方法时的入参)的对数次,比如如果数组长度是8,那么就循环3次,因为2的3次方等于8
//循环对数次的目的一个是不想不扫描,另一个是不想全部扫描,所以就取了这么一个次数
//对数次是怎么算出来的呢,就是(n >>>= 1) != 0,每次向右移一位,因为数组的长度不会是负数,所以这里>>>和>>其实是一样的
//2、如果循环过程中遇到了需要清理的元素,那么清理完成后再重新循环数组长度的对数次,直到没有需要清理的元素为止
//3、如果扫描过程中发生了清理,则返回true,否则false
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;
}
/**
* Re-pack and/or re-size the table. First scan the entire
* table removing stale entries. If this doesn't sufficiently
* shrink the size of the table, double the table size.
*/
private void rehash() {
//在进行扩容之前先进行一次全量的扫描,如果发现有失效的元素就进行清除,这个其实是比较耗时的
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
//如果清理完,发现元素的数量大于数组长度的一半(3/4 * 2/3)就要进行扩容了
if (size >= threshold - threshold / 4)
//扩容
resize();
}
/**
* 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 {
//计算k元素新的数组下标
int h = k.threadLocalHashCode & (newLen - 1);
//如果这个位置已经被设置了就找下一个位置(hash冲突)
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
//新增加的元素加1
count++;
}
}
}
//重新设置阈值(负载因子)
setThreshold(newLen);
//重新设置元素个数
size = count;
//重新设置数组
table = newTab;
}
/**
* 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);
}
}
}
}