基本结构
ThreadLocalMap是ThreadLocal的内部类,内部独立实现了Map功能、Entry功能。
成员变量
/**
* The initial capacity -- MUST be a power of two.
* 他的初始容量——必须是2的幂次方。
*/
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*
* 存放数据的table,根据需要调整大小。表格长度一定是2的幂次方。
*/
private ThreadLocal.ThreadLocalMap.Entry[] table;
/**
* The number of entries in the table.
* 数组里面entrys的个数,可以用于判断table当前使用量是否超过阈值
*/
private int size = 0;
/**
* The next size value at which to resize.
* 要调整大小的下一个大小值。/进行扩容的阈值,表使用量大于它时扩容
*/
private int threshold; // Default to 0
和Map一样,INITIAL_CAPACITY 代表这个Map的初始容量,table是一个Entry类型的数组,用于存储数据,threshold是扩容阈值。
/**
* 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.
*
* 这个散列映射中的条目扩展了WeakReference,使用它的主ref字段作为键
* (它总是一个*ThreadLocal对象)。注意空键(即。入口.get()*==null)
* 表示不再引用该键,因此可以从表中删除项。在下面的代码中,这些条目被称为“过时条目”。
*
* Entry继承WeakRefefence,并且用ThreadLocal作为key.
* 如果key为nu11(entry.get()==nu11),意味着key不再被引用,
* 因此这时候entry也可以从table中清除。
*
* Entry继承WeakReference,也就是key(ThreadLocal)是弱引用,
* 其目的是将ThreadLocal对象的生命周期和线程生命周期解绑。
*
* WeakReference 弱引用
* 垃圾回收期一旦发现了具有弱引用的对象,不管内存空间十分足够,都会回收内存。
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. 与此ThreadLocal关联的值 */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
使用ThreadLocal的一些问题
1.使用ThreadLocal产生内存泄露是因为ThreadLocalMap中的Entry继承了WeakReference(Key ThreadLocal是弱引用)?
首先看第一个,使用ThreadLocal产生内存泄露是因为ThreadLocalMap中的Entry继承了WeakReference(Key ThreadLocal是弱引用)这个理解有误的。下面看下这些名词。
Java有四种引用方式:强、弱、软、虚。这边主要看强引用、弱引用。
强引用(Strong Reference):
就是常见的对象引用(比如New),这种是只要还有一个强引用指向一个对象,就表明这个对象还货值,垃圾收集器就不会回收该对象。
弱引用(WeakReference):
垃圾收集器一旦发现了只具有弱引用的对象,不管内存空间是否足够,都会回收它的内存。
Java内存溢出(Memory overflow):
没有足够的内存空间给申请者使用,内存不足(对象所需的空间大于Head剩下的空间)。
Java内存泄漏(Memory leak):
是指程序中已经动态分配的堆内存由于某种原因程序未释放或者无法释放,造成系统内存的浪费,导致程序运行缓慢甚至崩溃,内存泄漏的堆积最终导致内存溢出。
其实不管ThreadLocalMap的Entry Key是强引用还是弱引用,都无法完全避免内存泄漏。
强引用:
假设在业务代码中使用完ThreadLocal,ThreadLocal Ref 被回收了,但是由于Entry中Key强引用了ThreadLocal,造成ThreadLocal无法被回收,在没有手动删除这个Entry以及CurrentThread运行的情况下,始终有强引用链ThreadRef>CurrentThread>ThreadLocalMap>Entry,Entry就不会被回收(Entry包含了ThreadLocal/Value),导致Entry内存泄漏。
弱引用:
假设在业务代码中使用完ThreadLocal,ThreadLocal Ref 被回收了,由于ThreadLocalMap只持有ThreadLocal的弱引用,没有任何强引用指向ThreadLocal实例,所以ThreadLocal被GC顺利回收,此时Entry的Key为null,在没有手动删除这个Entry以及CurrentThread运行的情况下,始终有强引用链,ThreadRef>CurrentThread>ThreadLocalMap>Entry>Value,Value就不会被回收,但是是Key为null,Value访问不到,导致Value内存泄漏。
其实不管强引用还是弱引用,在产生内存泄漏的时候有两个前提:
1.没有手动删除这个Entry;2.CurrentThread正常运行;
第一个可以在使用完ThreadLocal之后调用Remove方法删除对应的Entry,避免内存泄漏。
第二个由于ThreadLocalMap是Thread的一个属性,被当前线程使用,所以它的生命周期和Thread一样,那在使用完ThreadLocal之后,Thread线程也随之执行结束,ThreadLocalMap自然会被GC回收,避免内存泄漏。
只有记得使用完ThreadLocal之后,手动调用Remove()方法删除对应的Entry,无论Key是强引用还是弱引用都不会有问题。
那为什么要使用弱引用?
在ThreadLocalMap类中的set()/getEntry()方法中,会对Key为null(就是ThreadLocal为null)进行判断,如果为null,value也会设置为null。这就意味着,使用完ThreadLocal之后CurrentThread正常运行的前提下,就算忘记调用Remove()方法,弱引用比强引用多一层保障,弱引用ThreadLocal会被回收,对应的value会在下一次ThreadLocalMap调用get/set/remove方法时清除,避免内存泄漏。
2.ThreadLocalMap中的Hash冲突解决?
Hash冲突的解决时Map中的一个重要内容,我们以这个问题为线索,看下ThreadLocalMap的源码
首先ThreadLocal的Set()方法
public void set(T value) {
// 获取当前线程对象
Thread t = Thread.currentThread();
// 获取ThreadLocalMap
ThreadLocal.ThreadLocalMap map = getMap(t);
if (map != null)
// 存在则set当前线程对象Entry
map.set(this, value);
else
// 如果当前线程不存在ThreadLocalMap对像,则调用createMap创建ThreadLocalMap对象,
// 并将t(当前线程对象), value(t对应的值)作为第一个Entry放入到ThreadLocalMap中
createMap(t, value);
}
void createMap(Thread t, T firstValue) {
// 调用了ThreadLocalMap的构造方法
t.threadLocals = new ThreadLocal.ThreadLocalMap(this, firstValue);
}
再看ThreadLocalMap的构造方法
/**
* 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.
*
* firstmap(最初包含一个新的键值)。ThreadLocalMaps是延迟构造的,
* 因此只有在至少有一个条目要放入时才创建。
*/
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
// 初始化Table
table = new ThreadLocal.ThreadLocalMap.Entry[INITIAL_CAPACITY];
// 计算索引下标
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
// 设置值
table[i] = new ThreadLocal.ThreadLocalMap.Entry(firstKey, firstValue);
size = 1;
// 设置阈值
setThreshold(INITIAL_CAPACITY);
}
重点看下这个方法
// 计算索引
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
/**
* 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.
*
* 线程局部变量依赖于每个线程附加的每线程线性探测哈希映射(Thread.threadLocals和
* InheritableShreadLocals)。ThreadLocal对象充当键,
* 通过threadLocalHashCode进行搜索。这是一个自定义哈希代码
* (仅在ThreadLocalMaps中有用),在连续构造的ThreadLocalMaps
* 被同一线程使用的情况下,它消除了冲突,
* 而在不常见的情况下,它仍然表现良好。
*/
private final int threadLocalHashCode = nextHashCode();
/**
* The next hash code to be given out. Updated atomically. Starts at
* zero.
* 下一个要给出的哈希代码。原子更新。从零开始
* AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式操作加减,适合高并发情况下使用
*/
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.
*
* 连续生成的两个近似乘性散列值的隐式散列值转化为两个近似最佳幂的局部散列码
* 特殊的Hash值-避免hash冲突
*/
private static final int HASH_INCREMENT = 0x61c88647;
/**
* Returns the next hash code.
* 返回下一个哈希代码
*/
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
这里定义了一个Atomiclnteger类型,每次获取当前值并加上HASHINCREMENT,HASH_INCREMENT = 0x61c88647,这个值跟斐波那契数列(黄金分割数)有关,其主要目的就是为了让哈希码能均匀的分布在2的n次方的数组里,也就是EntryI table中,这样做可以尽量避免hash冲突。
关于&(INITIAL_CAPACITY-1)
计算hash的时候里面采用了hashCode&(size-1)的算法,这相当于取模运算hashCode%size的一个更高效的实现。正是因为这种算法,我们要求size必须是2的整次幂,这也能保证保证在索引不越界的前提下,使得hash发生冲突的次数减小。
Set()方法
/**
* 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.
/**
* 我们没有像get()那样使用快速路径,因为使用set()创建新条目与
* 替换现有条目一样常见,在这种情况下,快速路径失败的次数更多。
*/
// 获取当前表空间
ThreadLocal.ThreadLocalMap.Entry[] tab = table;
int len = tab.length;
// 计算索引
int i = key.threadLocalHashCode & (len-1);
// 使用线性探测法查找元素
for (ThreadLocal.ThreadLocalMap.Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
// ThreadLocal对应的key存在,则覆盖之前的值 value
if (k == key) {
e.value = value;
return;
}
// k为空(如果没有设置过值),value 不为空则说明之前的ThreadLocal对象已经被回收了
// 当前数组中的Entry是一个陈旧(stale)的元素
if (k == null) {
// 替换过时项(空值),用新元素替换旧元素,这个方法里进行了垃圾清理动作,放置内存泄露
replaceStaleEntry(key, value, i);
return;
}
}
// ThreadLocal对应的key不存在并且没有找到陈旧的元素,则在空元素的位置创建一个新的Entry
tab[i] = new ThreadLocal.ThreadLocalMap.Entry(key, value);
int sz = ++size;
/**
* cleanSomeSlots()方法用于清除(e != null && e.get() == null)的元素
* 这种数据Key关联的对象已经被回收,所以这个Entry(table[index])可以被设置为null
* 如果没有清除任何entry且当前使用量(数组的长度)大于负载因子定义的(长度的2/3),
* 那么则进行rehash()-执行一次全表的扫描清理工作
*/
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
/**
* Increment i modulo len.
*/
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
首先还是根据key计算出索引i,然后查找位置上的Entry,
若是Entry已经存在并且key等于传入的key,那么这时候直接给这个Entry赋新的value值,
若是Entry存在,但是key为null,则调用replaceStaleEntry来更换这个key为空的Entry,
不断循环检测,直到遇到为null的地方,这时候要是还没在循环过程中return,那么就在这个null的位置新建一个Entry,并且插入,同时size增加1。
最后调用cleanSomeSlots,清理key为null的Entry,最后返回是否清理了Entry,接下来再判断sz是否>= thresgold达到了rehash的条件,达到的话就会调用rehash函数执行一次全表的扫描清理。
线性探测法解决Hash冲突
该方法一次探测下一个地址,直到有空的地址后插入,若整个空间都找不到空余的地址,则产生溢出。
举个例子,假设当前table长度为16,也就是说如果计算出来key的hash值为14,如果table[14]上已经有值,并且其key与当前key不一致,那么就发生了hash冲突,这个时候将1401得到15,取table[15]进行判断,这个时候如果还是冲突会回到0,取table[0],以此类推,直到可以插入。 按照上面的描述,可以把Entry table看成一个环形数组。
ThreadLocal使用场景
ThreadLocal的作用主要是做数据隔离,填充的数据只属于当前线程,变量的数据对别的线程而言是相对隔离的,在多线程环境下,如何防止自己的变量被其它线程篡改。
例如,用于 Spring实现事务隔离级别的源码 Spring采用Threadlocal的方式,来保证单个线程中的数据库操作使用的是同一个数据库连接,同时,采用这种方式可以使业务层使用事务时不需要感知并管理connection对象,通过传播级别,巧妙地管理多个事务配置之间的切换,挂起和恢复。 Spring框架里面就是用的ThreadLocal来实现这种隔离,主要是在`TransactionSynchronizationManager`这个类里面,代码如下所示:
private static final Log logger = LogFactory.getLog(TransactionSynchronizationManager.class);
private static final ThreadLocal<Map<Object, Object>> resources =
new NamedThreadLocal<>("Transactional resources");
private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations =
new NamedThreadLocal<>("Transaction synchronizations");
private static final ThreadLocal<String> currentTransactionName =
new NamedThreadLocal<>("Current transaction name");
### 用户使用场景1
除了源码里面使用到ThreadLocal的场景,你自己有使用他的场景么?
之前我们上线后发现部分用户的日期居然不对了,排查下来是SimpleDataFormat的锅,当时我们使用SimpleDataFormat的parse()方法,内部有一个Calendar对象,调用SimpleDataFormat的parse()方法会先调用Calendar.clear(),然后调用Calendar.add(),如果一个线程先调用了add()然后另一个线程又调用了clear(),这时候parse()方法解析的时间就不对了。 其实要解决这个问题很简单,让每个线程都new 一个自己的 SimpleDataFormat就好了,但是1000个线程难道new1000个SimpleDataFormat? 所以当时我们使用了线程池加上ThreadLocal包装SimpleDataFormat,再调用initialValue让每个线程有一个SimpleDataFormat的副本,从而解决了线程安全的问题,也提高了性能。
### 用户使用场景2
我在项目中存在一个线程经常遇到横跨若干方法调用,需要传递的对象,也就是上下文(Context),它是一种状态,经常就是是用户身份、任务信息等,就会存在过渡传参的问题。
使用到类似责任链模式,给每个方法增加一个context参数非常麻烦,而且有些时候,如果调用链有无法修改源码的第三方库,对象参数就传不进去了,所以我使用到了ThreadLocal去做了一下改造,这样只需要在调用前在ThreadLocal中设置参数,其他地方get一下就好了。
@Slf4j
public class DateFormatTest {
/**
* 问题:
* 之前我们上线后发现部分用户的日期居然不对了,排查下来是SimpleDataFormat的锅,
* 当时我们使用SimpleDataFormat的parse()方法,内部有一个Calendar对象,
* 调用SimpleDataFormat的parse()方法会先调用Calendar.clear(),然后调用Calendar.add(),
* 如果一个线程先调用了add()然后另一个线程又调用了clear(),这时候parse()方法解析的时间就不对了。
* 其实要解决这个问题很简单,让每个线程都new 一个自己的 SimpleDataFormat就好了,
* 但是1000个线程难道new1000个SimpleDataFormat?
* 所以当时我们使用了线程池加上ThreadLocal包装SimpleDataFormat,
* 再调用initialValue让每个线程有一个SimpleDataFormat的副本,
* 从而解决了线程安全的问题,也提高了性能。
*/
public static Date testDataFormart() throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String dateStr = simpleDateFormat.format(new Date());
return simpleDateFormat.parse(dateStr);
}
public static void testDataFormartNoThreadLocal(){
for (int i = 0; i < 500; i++) {
new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
log.info("打印线程" +Thread.currentThread().getName()+"的日期"+testDataFormart());
}
}).start();
}
}
/**
* 创建ThreadLocal Map集合
*/
private static final ThreadLocal<Map<String, SimpleDateFormat>> mapThreadLocal = new ThreadLocal<Map<String, SimpleDateFormat>>(){
@Override
public Map<String, SimpleDateFormat> initialValue(){
return new HashMap<String, SimpleDateFormat>();
}
};
/**
* 获取线程局部变量
* @param dateFormat
* @return
*/
private static SimpleDateFormat getDateFormat(String dateFormat) {
Map<String, SimpleDateFormat> formatters = mapThreadLocal.get();
SimpleDateFormat formatter = formatters.get(dateFormat);
if (formatter == null)
{
formatter = new SimpleDateFormat(dateFormat);
formatters.put(dateFormat, formatter);
}
return formatter;
}
public static void testDataFormartThreadLocal() throws ParseException {
List<Future<Date>> list = new ArrayList<>();
for (int i = 0; i < 500; i++) {
ExecutorService executorService = Executors.newScheduledThreadPool(10);
Future<Date> future = executorService.submit(new Callable<Date>() {
@Override
public Date call() throws Exception {
SimpleDateFormat simpleDateFormat = getDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS'Z'");
String dateStr = simpleDateFormat.format(new Date());
Date date = simpleDateFormat.parse(dateStr);
return date;
}
});
list.add(future);
}
list.forEach(dateFuture -> {
try {
log.info("打印线程" +Thread.currentThread().getName()+"的日期"+dateFuture.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
}
public static void main(String[] args) {
try {
//testDataFormartNoThreadLocal();
testDataFormartThreadLocal();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
附ThreadLocalMap源码注释:
package com.yl.springboottest.thread.threadlocal;
import java.lang.ref.WeakReference;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
/**
* 描述: ThreadLocal 线程局部变量类源码解析
*
* @author: yanglin
* @Date: 2020-10-15-15:50
* @Version: 1.0
*/
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.
*
* 线程局部变量依赖于每个线程附加的每线程线性探测哈希映射(Thread.threadLocals和
* InheritableShreadLocals)。ThreadLocal对象充当键,
* 通过threadLocalHashCode进行搜索。这是一个自定义哈希代码
* (仅在ThreadLocalMaps中有用),在连续构造的ThreadLocalMaps
* 被同一线程使用的情况下,它消除了冲突,
* 而在不常见的情况下,它仍然表现良好。
*/
private final int threadLocalHashCode = nextHashCode();
/**
* The next hash code to be given out. Updated atomically. Starts at
* zero.
* 下一个要给出的哈希代码。原子更新。从零开始
* AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式操作加减,适合高并发情况下使用
*/
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.
*
* 连续生成的两个近似乘性散列值的隐式散列值转化为两个近似最佳幂的局部散列码
* 特殊的Hash值-避免hash冲突
*/
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}.
*
* 返回此thread局部变量的当前线程的“初始值”。此方法将在线程第一次使用{@link#get}方法访问变量时调用,
* 除非线程先前调用了{@link}set}方法,在这种情况下,{@code initialValue}方法将不会为线程调用。
* 通常,每个线程最多调用一次此方法,但如果后续调用{@link#remove},然后调用{@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.
*
*
* <p>此实现只返回{@code null};如果程序员希望线程局部变量的初始值不是{@code null},
* 则{@code ThreadLocal}必须子类化,并重写此方法。通常,将使用匿名内部类
*
* @return the initial value for this thread-local
* 此线程本地的初始值
* (备注:该方法是一个protected的方法,显然是为了让子类覆盖而设计的)
*/
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 ThreadLocal.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.
*
* 返回此thread局部变量的当前线程副本中的值。如果变量对于current线程没有值,
* 它首先被初始化为通过调用{@link}initialValue}方法返回的值。
*
* @return the current thread's value of this thread-local
*/
public T get() {
// 获取当前线程对象
Thread t = Thread.currentThread();
// 获取此线程对象中维护的ThreadLocalMap对象
ThreadLocal.ThreadLocalMap map = getMap(t);
// 判断NULL
if (map != null) {
// 以当前线程对象为Key,调用getEntry()获取对应的存储实体e
ThreadLocal.ThreadLocalMap.Entry e = map.getEntry(this);
// 判断存储实体e
if (e != null) {
@SuppressWarnings("unchecked")
// 获取存储实体e对应的Value,即为当前线程对应的ThreadLocal对象
T result = (T)e.value;
return result;
}
}
/**
* 如果map为null,则初始化
* 两种情况
* 第一种情况:map不存在,标识当前线程没有维护的ThreadLocalMap对象
* 第二种情况:map存在,但是没有与当前的ThreadLocal关联的Entry
*/
return setInitialValue();
}
/**
* Variant of set() to establish initialValue. Used instead
* of set() in case user has overridden the set() method.
*
* 当前线程初始化ThreadLocal.ThreadLocalMap
*
* @return the initial value
*/
private T setInitialValue() {
// 获取初始化的值,此方法可以被子类重写,如果不重写默认返回NULL
T value = initialValue();
// 获取当前线程对象
Thread t = Thread.currentThread();
// 获取ThreadLocalMap
ThreadLocal.ThreadLocalMap map = getMap(t);
// 判断NULL
if (map != null)
// 存在则set当前线程对象Entry
map.set(this, value);
else
// 如果当前线程不存在ThreadLocalMap对像,则调用createMap创建ThreadLocalMap对象,
// 并将t(当前线程对象), value(t对应的值)作为第一个Entry放入到ThreadLocalMap中
createMap(t, value);
// 返回设置的值
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.
*
* 将此线程局部变量的当前线程副本设置为指定值。大多数子类不需要*重写这个方法,
* 只依赖{@link#initialValue}方法来设置线程局部变量的值。
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
* 要存储在当前线程的this thread local副本中的值。
*/
public void set(T value) {
// 获取当前线程对象
Thread t = Thread.currentThread();
// 获取ThreadLocalMap
ThreadLocal.ThreadLocalMap map = getMap(t);
if (map != null)
// 存在则set当前线程对象Entry
map.set(this, value);
else
// 如果当前线程不存在ThreadLocalMap对像,则调用createMap创建ThreadLocalMap对象,
// 并将t(当前线程对象), value(t对应的值)作为第一个Entry放入到ThreadLocalMap中
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.
*
* 删除此线程局部变量的当前线程值。如果此线程局部变量随后被当前线程{@linkplain get read},
* 则其值将通过调用其{@link#initialValue}方法重新初始化,除非它的值在此期间是当前线程的
* {@linkplain#set}。这可能导致在当前线程中多次调用{@code initialValue}方法
*
* 删除当前线程对象中维护的ThreadLocalMap对象
*
* @since 1.5
*/
public void remove() {
// 获取当前线程对象中的ThreadLocalMap对象
ThreadLocal.ThreadLocalMap m = getMap(Thread.currentThread());
// 验证
if (m != null)
// 以当前ThreadLocal对象为Key删除对应的实体Entry
m.remove(this);
}
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocal.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 ThreadLocal.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 ThreadLocal.ThreadLocalMap createInheritedMap(ThreadLocal.ThreadLocalMap parentMap) {
return new ThreadLocal.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.
*
* 这个散列映射中的条目扩展了WeakReference,使用它的主ref字段作为键
* (它总是一个*ThreadLocal对象)。注意空键(即。入口.get()*==null)
* 表示不再引用该键,因此可以从表中删除项。在下面的代码中,这些条目被称为“过时条目”。
*
* Entry继承WeakRefefence,并且用ThreadLocal作为key.
* 如果key为nu11(entry.get()==nu11),意味着key不再被引用,
* 因此这时候entry也可以从table中清除。
*
* Entry继承WeakReference,也就是key(ThreadLocal)是弱引用,
* 其目的是将ThreadLocal对象的生命周期和线程生命周期解绑。
*
* WeakReference 弱引用
* 垃圾回收期一旦发现了具有弱引用的对象,不管内存空间十分足够,都会回收内存。
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. 与此ThreadLocal关联的值 */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* The initial capacity -- MUST be a power of two.
* 他的初始容量——必须是2的幂次方。
*/
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*
* 存放数据的table,根据需要调整大小。表格长度一定是2的幂次方。
*/
private ThreadLocal.ThreadLocalMap.Entry[] table;
/**
* The number of entries in the table.
* 数组里面entrys的个数,可以用于判断table当前使用量是否超过阈值
*/
private int size = 0;
/**
* The next size value at which to resize.
* 要调整大小的下一个大小值。/进行扩容的阈值,表使用量大于它时扩容
*/
private int threshold; // Default to 0
/**
* Set the resize threshold to maintain at worst a 2/3 load factor.
* 设置resize threshold以在最坏的情况下保持2/3的负载系数。
*/
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.
*
* firstmap(最初包含一个新的键值)。ThreadLocalMaps是延迟构造的,
* 因此只有在至少有一个条目要放入时才创建。
*/
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
// 初始化Table
table = new ThreadLocal.ThreadLocalMap.Entry[INITIAL_CAPACITY];
// 计算索引下标
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
// 设置值
table[i] = new ThreadLocal.ThreadLocalMap.Entry(firstKey, firstValue);
size = 1;
// 设置阈值
setThreshold(INITIAL_CAPACITY);
}
/**
* Construct a new map including all Inheritable ThreadLocals
* from given parent map. Called only by createInheritedMap.
*
* 构造一个新的映射,包括给定父映射中所有可继承的ThreadLocals。仅由createInheritedMap调用。
*
* @param parentMap the map associated with parent thread.
*/
private ThreadLocalMap(ThreadLocal.ThreadLocalMap parentMap) {
ThreadLocal.ThreadLocalMap.Entry[] parentTable = parentMap.table;
int len = parentTable.length;
setThreshold(len);
table = new ThreadLocal.ThreadLocalMap.Entry[len];
for (int j = 0; j < len; j++) {
ThreadLocal.ThreadLocalMap.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);
ThreadLocal.ThreadLocalMap.Entry c = new ThreadLocal.ThreadLocalMap.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.
*
* 获取与key关联的条目。此方法本身只处理快速路径:直接命中现有键。否则,
* 它会在未命中后中继到getEntryAfterMiss。这是为了最大限度地提高直接命中的性能,
* 在某种程度上,通过使这种方法易于内联。
*
* @param key the thread local object
* @return the entry associated with key, or null if no such
*/
private ThreadLocal.ThreadLocalMap.Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
ThreadLocal.ThreadLocalMap.Entry e = table[i];
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}
/**
* Version of getEntry method for use when key is not found in
* its direct hash slot.
*
* 在直接哈希槽中找不到键时使用的getEntry方法的版本。
*
* @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 ThreadLocal.ThreadLocalMap.Entry getEntryAfterMiss(ThreadLocal<?> key, int i, ThreadLocal.ThreadLocalMap.Entry e) {
ThreadLocal.ThreadLocalMap.Entry[] tab = table;
int len = tab.length;
while (e != null) {
ThreadLocal<?> k = e.get();
// 如何Key一致(当前线程ThreadLocal),直接返回
if (k == key)
return e;
// 如何Key为空
if (k == null)
expungeStaleEntry(i);
else
// 下一个
i = nextIndex(i, len);
e = tab[i];
}
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.
/**
* 我们没有像get()那样使用快速路径,因为使用set()创建新条目与
* 替换现有条目一样常见,在这种情况下,快速路径失败的次数更多。
*/
// 获取当前表空间
ThreadLocal.ThreadLocalMap.Entry[] tab = table;
int len = tab.length;
// 计算索引
int i = key.threadLocalHashCode & (len-1);
// 使用线性探测法查找元素
for (ThreadLocal.ThreadLocalMap.Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
// ThreadLocal对应的key存在,则覆盖之前的值 value
if (k == key) {
e.value = value;
return;
}
// k为空(如果没有设置过值),value 不为空则说明之前的ThreadLocal对象已经被回收了
// 当前数组中的Entry是一个陈旧(stale)的元素
if (k == null) {
// 替换过时项(空值),用新元素替换旧元素,这个方法里进行了垃圾清理动作,放置内存泄露
replaceStaleEntry(key, value, i);
return;
}
}
// ThreadLocal对应的key不存在并且没有找到陈旧的元素,则在空元素的位置创建一个新的Entry
tab[i] = new ThreadLocal.ThreadLocalMap.Entry(key, value);
int sz = ++size;
/**
* cleanSomeSlots()方法用于清除(e != null && e.get() == null)的元素
* 这种数据Key关联的对象已经被回收,所以这个Entry(table[index])可以被设置为null
* 如果没有清除任何entry且当前使用量(数组的长度)大于负载因子定义的(长度的2/3),
* 那么则进行rehash()-执行一次全表的扫描清理工作
*/
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
/**
* Remove the entry for key.
*
* 移除
*/
private void remove(ThreadLocal<?> key) {
ThreadLocal.ThreadLocalMap.Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
// 遍历
for (ThreadLocal.ThreadLocalMap.Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
if (e.get() == key) {
// 移除Entry
e.clear();
expungeStaleEntry(i);
return;
}
}
}
/**
* entry 条目
*
* 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.
*
* 将set操作期间遇到的过时项替换为指定键的项。传入value参数的值存储在条目中,
* 无论指定键是否已存在项。
*
* 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.)
*
* 作为一个副作用,此方法将删除“run”中包含该过时项的所有过时项。(运行是两个空槽之间的一系列条目。)
*
* @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) {
ThreadLocal.ThreadLocalMap.Entry[] tab = table;
int len = tab.length;
ThreadLocal.ThreadLocalMap.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;
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 查找run的键或尾随的null slot,以最先出现的为准
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.
/**
* 如果找到键,则需要将它与过时的条目交换,以保持哈希表的顺序。然后,
* 可以将新过时的插槽或其上方遇到的任何其他陈旧插槽发送到expungeStaleEntry
* 以删除或重新计算运行中的所有其他条目。
*/
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 ThreadLocal.ThreadLocalMap.Entry(key, value);
// If there are any other stale entries in run, expunge them 如果有其他条目,请删除它们
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
*
* 通过重新整理位于staleSlot和下一个空slot之间的任何可能发生冲突的条目来清除过时条目。
* 这还将删除在尾随的null之前遇到的任何其他过时条目。
* 参见Knuth,第6.4节
*
* Slot JVM 局部变量表最基本的存储单元(变量槽)
*
* @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之后的下一个空槽的索引(staleSlot和此slot之间的所有内容都将被检查以进行清除)。
*/
private int expungeStaleEntry(int staleSlot) {
// 当前表空间
ThreadLocal.ThreadLocalMap.Entry[] tab = table;
int len = tab.length;
// expunge entry at staleSlot 删除staleSlot中的条目
// 删除数组中值
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
// Rehash until we encounter null 重新计算直到我们遇到空值
ThreadLocal.ThreadLocalMap.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 与Knuth 6.4算法R不同,我们必须扫描到
// null because multiple entries could have been stale. null,因为多个条目可能已过时。
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.
*
* 试探性地扫描一些单元格,寻找过时的条目。当添加新元素或删除另一个过时的元素时,
* 将调用此函数。它执行一个*数扫描次数,作为无扫描(快速但保留垃圾)和扫描次数
* 之间的平衡,扫描次数与元素数量成比例,这将查找所有垃圾,但会导致一些插入花费O(n)时间。
*
* @param i a position known NOT to hold a stale entry. The
* scan starts at the element after i.
* 已知不包含过时条目的位置。扫描从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.)
*
* 扫描控制:{@codelog2(n)}单元格被扫描,除非找到过时的条目,在这种情况下
* {@codelog2(表格长度)-1} 扫描其他单元格。当从insertions调用时,此参数是元素
* 的数目但是从replaceStateEntry调用时,它是表长度。(注意:所有这些都可以
* 通过加权n而不是仅仅使用直接对数n来改变为或多或少的攻击性。
* 但是这个版本简单、快速,而且似乎工作得很好。)
*
* @return true if any stale entries have been removed.
* 如果删除了任何过时的条目,则为true。
*/
private boolean cleanSomeSlots(int i, int n) {
boolean removed = false;
ThreadLocal.ThreadLocalMap.Entry[] tab = table;
int len = tab.length;
do {
i = nextIndex(i, len);
ThreadLocal.ThreadLocalMap.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
if (size >= threshold - threshold / 4)
resize();
}
/**
* Double the capacity of the table.
*/
private void resize() {
ThreadLocal.ThreadLocalMap.Entry[] oldTab = table;
int oldLen = oldTab.length;
int newLen = oldLen * 2;
ThreadLocal.ThreadLocalMap.Entry[] newTab = new ThreadLocal.ThreadLocalMap.Entry[newLen];
int count = 0;
for (int j = 0; j < oldLen; ++j) {
ThreadLocal.ThreadLocalMap.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;
}
/**
* Expunge all stale entries in the table.
*/
private void expungeStaleEntries() {
ThreadLocal.ThreadLocalMap.Entry[] tab = table;
int len = tab.length;
for (int j = 0; j < len; j++) {
ThreadLocal.ThreadLocalMap.Entry e = tab[j];
if (e != null && e.get() == null)
expungeStaleEntry(j);
}
}
}
}
## 参考 https://blog.csdn.net/qq_35190492/article/details/107599875