ThreadLocal的作用就是在线程内部创建一个变量副本,ThreadLocal的思想就是用空间换时间,使各线程都能访问自己的变量副本,ThreadLocal虽然提供了一种解决多线程环境下成员变量的问题,但是它并不是解决多线程环境下共享变量的问题,本文就以ThreadLocal源码为例深入探讨它的结构实现和功能原理。
JDK的文档介绍
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).
该类提供了线程局部变量,这些变量与普通变量不同,每个线程都可以通过 get 或 set方法来访问自己的变量副本。ThreadLocal 实例通常是类中私有的,它们希望将状态与某一个线程(用户ID或事务ID)相关联,实现线程之间的数据隔离。
ThreadLocal源码剖析
每个线程Thread维护一个ThreadLocalMap,而ThreadLocalMap的内部就是以Entry为元素的table数组,Entry就是一个key-value结构,key就是ThreadLocal value为实际存储的值,这里的ThreadLocal和key之间的虚线,是因为Entry是继承WeakReference实现的,当ThreadLocal Ref销毁时,指向堆中ThreadLocal实例的唯一一条强引用消失了,只有Entry有一条指向ThreadLocal实例的弱引用,那么这里的ThreadLocal实例是可以被GC掉的。这时Entry里的key为null,那么直到线程结束前Entry中的value都是无法回收的,这里可能产生内存泄露。
成员变量
//初始容量 —— 必须是2的冥
private static final int INITIAL_CAPACITY = 16;
//存放数据的数组,数组长度必须是2的冥
private Entry[] table;
//数组中元素的个数
private int size = 0;
//进行扩容的阈值
private int threshold;
//设置扩容的阈值大小,使其在最坏情况下保持2/3的负载系数
private void setThreshold(int len) {threshold = len * 2 / 3;}
Entry结构
//Entry继承WeakReference使用弱引用的方式[为了降低内存泄漏发生的概率]
//entry.get() == null表示key不再被引用 ThreadLocal对象可被回收,它的key如果没被强引用会在GC触发的时候回收掉
//我们在使用ThreadLocal的时候,每次用完ThreadLocal都调用remove()方法,清除数据,防止内存泄漏
static class Entry extends WeakReference> {
/** The value associated with this ThreadLocal. */
Object value;
//并且使用ThreadLocal作为key
Entry(ThreadLocal> k, Object v) {
super(k);
value = v;
}
}
set(T value)源码分析
public void set(T value) {
//获取当前线程
Thread t = Thread.currentThread();
//根据当前线程获取ThreadLocalMap[相当于hashMap,真正保存数据的地方]
ThreadLocalMap map = getMap(t);
if (map != null)
//map不为空赋值,并用当前ThreadLocal作为key
map.set(this, value);
else
//成员变量中的ThreadLocalMap还没被创建,则创建ThreadLocalMap,给当前线程使用并保存value
createMap(t, value);
}
//获取Thread的成员变量threadLocals
ThreadLocalMap getMap(Thread t) {
//每一个线程都会持有有一个ThreadLocalMap,用来维护线程本地的值
//threadLocals --> public class Thread implements Runnable的成员属性
return t.threadLocals;
}
//调用的是new ThreadLocalMap();
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
//ThreadLocalMap构造方法
ThreadLocalMap(ThreadLocal> firstKey, Object firstValue) {
//创建和初始化table容量默认值是16,主要数据结构就是一个Entry数组
table = new Entry[INITIAL_CAPACITY];
//计算hash值获取数组下标地址
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
//创建Entry,存放第一个数据
table[i] = new Entry(firstKey, firstValue);
//记录ThreadLocalMap中的Entry个数
size = 1;
//设置扩容阀值,当size到达threashold时需要resize整个ThreadLocalMap
setThreshold(INITIAL_CAPACITY);
}
//每次创建ThreadLocal都会加HASH_INCREMENT,重新计算threadLocalHashCode值
private final int threadLocalHashCode = nextHashCode();
//使用AtomicInteger保证多线程环境下的同步
private static AtomicInteger nextHashCode = new AtomicInteger();
//魔数的选取是为了让HashCode能够均匀的分布在2的N次方的数组里
private static final int HASH_INCREMENT = 0x61c88647;
//计算ThreadLocal对象的HashCode
private static int nextHashCode() {
//每次增加HASH_INCREMENT
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
//扩容的阀值是容量的2/3,len = 16计算结果等于10
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
map.set(this, value)源码分析
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.
//初始化table
Entry[] tab = table;
//获取tab的长度
int len = tab.length;
//快速hash获取下标地址
int i = key.threadLocalHashCode & (len-1);
//用线性探测法解决冲突,调用nextIndex(i, len)遍历table
//循环判断要存放的索引位置是否已经存在 Entry,若存在(tab[i])则进入循环体
for (Entry e = tab[i];e != null;e = tab[i = nextIndex(i, len)]) {
//获取ThreadLocal对象,也就是key
ThreadLocal> k = e.get();
if (k == key) {
//如果索引位置Entry的key已经存在,重新设置值
e.value = value;
return;
}
//如果索引位置的 Entry的存在,但是key为null(key已被回收过)
if (k == null) {
//更换当前key为null的Entry
replaceStaleEntry(key, value, i);
return;
}
}
//存放的索引位置没有Entry,将当前的[key,value]作为一个Entry保存在该位置
tab[i] = new Entry(key, value);
//增加ThreadLocalMap中的Entry个数
int sz = ++size;
//清理key为null的Entry并判断table中的数量是否超出阈值
if (!cleanSomeSlots(i, sz) && sz >= threshold)
//扩容调整table的容量
rehash();
}
private void replaceStaleEntry(ThreadLocal> key, Object value,int staleSlot) {
Entry[] tab = table;
int len = tab.length;
Entry e;
//默认初始值
int slotToExpunge = staleSlot;
//向前遍历找到key为null的位置,记录为slotToExpunge,
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
//向后遍历,若是key相等,给这个Entry赋新的value值
for (int i = nextIndex(staleSlot, len);(e = tab[i]) != null;i = nextIndex(i, len)){
ThreadLocal> k = e.get();
if (k == key) {
e.value = value;
//和staleSlot位置的Entry交换
tab[i] = tab[staleSlot];
tab[staleSlot] = e;
// Start expunge at preceding stale entry if it exists
if (slotToExpunge == staleSlot)
slotToExpunge = i;
//调用CleanSomeSlots清理key为null的Entry
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
return;
}
if (k == null && slotToExpunge == staleSlot)
slotToExpunge = i;
}
// If key not found, put new entry in stale slot
//没有Entry的key和传入key相等,就在staleSlot位置新建一个Entry
tab[staleSlot].value = null;
tab[staleSlot] = new Entry(key, value);
// If there are any other stale entries in run, expunge them
if (slotToExpunge != staleSlot)
//再清理一遍key为null的Entry[为了降低内存泄漏发生的可能]
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
//cleanSomeSlots(int i, int n)
//这个方法可能不是清理所有的entry,而是简单快速的清理几个entry
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;
//调用expungeStaleEntry(i)去清理
i = expungeStaleEntry(i);
}
//log2(n)清理次数
} while ( (n >>>= 1) != 0);
return removed;
}
//rehash
private void rehash() {
//清理key为null的Entry
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
//如果size大于3/4的threshold
if (size >= threshold - threshold / 4)
//resize
resize();
}
//expungeStaleEntries()
private void expungeStaleEntries() {
Entry[] tab = table;
int len = tab.length;
//遍历table,清理key为null的Entry
for (int j = 0; j < len; j++) {
Entry e = tab[j];
if (e != null && e.get() == null)
expungeStaleEntry(j);
}
}
//resize()
private void resize() {
//初始化oldTab
Entry[] oldTab = table;
//oldLen长度
int oldLen = oldTab.length;
//newLen新长度,扩容为原来的2倍
int newLen = oldLen * 2;
//初始化newTab
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) {
//清除key为null的Entry
e.value = null; // Help the GC
} else {
//重新计算key不为null的Entry的hash值
int h = k.threadLocalHashCode & (newLen - 1);
while (newTab[h] != null)
//线性探测法解决冲突
h = nextIndex(h, newLen);
//entry存储指定位置
newTab[h] = e;
count++;
}
}
}
//更新ThreadLocalMap成员属性
setThreshold(newLen);
size = count;
table = newTab;
}
get()源码分析
public T get() {
//获取当前线程
Thread t = Thread.currentThread();
//获取当前线程的ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null) {
//从当前线程的ThreadLocalMap获取相对应的Entry
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
//获取目标值
@SuppressWarnings("unchecked")
T result = (T) e.value;
return result;
}
}
//调用setInitialValue()方法返回初始值
return setInitialValue();
}
//getEntry(ThreadLocal> key)
private Entry getEntry(ThreadLocal> key) {
//计算指定key的hash值
int i = key.threadLocalHashCode & (table.length - 1);
//获取当前位置的Entry
Entry e = table[i];
//如果Entry不为null且Entry的key和指定的key相等,返回该Entry
if (e != null && e.get() == key)
return e;
else
//调用getEntryAfterMiss(ThreadLocal key, int i, Entry e)方法
return getEntryAfterMiss(key, i, e);
}
//getEntryAfterMiss(ThreadLocal> key, int i, Entry e)
private Entry getEntryAfterMiss(ThreadLocal> key, int i, Entry e) {
//初始化tab及长度
Entry[] tab = table;
int len = tab.length;
//索引位置上的Entry不为null进入循环,否则返回nul
while (e != null) {
ThreadLocal> k = e.get();
//如果Entry的key和指定的key相等,则返回该Entry
if (k == key)
return e;
//如果Entry的key为null[key已被回收],清除无效的Entry
if (k == null)
expungeStaleEntry(i);
else
//获取下一个位置的Entry,循环判断
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
initialValue()源码分析
private T setInitialValue() {
//该方法默认返回null,子类可以重写该方法,用于设置ThreadLocal初始值。
T value = initialValue();
//获取当前线程
Thread t = Thread.currentThread();
//获取当前线程的ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null)
//map不为空赋值,并用当前ThreadLocal作为key
map.set(this, value);
else
//线程中成员变量ThreadLocalMap还没被创建,创建ThreadLocalMap
createMap(t, value);
//默认返回null
return value;
}
remove(ThreadLocal> key) 源码分析
private void remove(ThreadLocal> key) {
//初始化table
Entry[] tab = table;
//计算table中数量
int len = tab.length;
//计算指定key的hash值
int i = key.threadLocalHashCode & (len-1);
//遍历table,循环判断索引位置的Entry是否为null
for (Entry e = tab[i];e != null;e = tab[i = nextIndex(i, len)]) {
//若Entry的key和指定的key相等,执行删除操作
if (e.get() == key) {
//清除Entry的key的引用
e.clear();
//清除无效的 Entry
expungeStaleEntry(i);
return;
}
}
}
//expungeStaleEntry(int staleSlot)
private int expungeStaleEntry(int staleSlot) {
//tab数组初始化及计算数组长度
Entry[] tab = table;
int len = tab.length;
// expunge entry at staleSlot
//删除value
tab[staleSlot].value = null;
//删除entry
tab[staleSlot] = null;
//map的size减1
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();
//key为null,执行删除操作
if (k == null) {
e.value = null;
tab[i] = null;
size--;
} else {
//key不为null,重新计算hash值
int h = k.threadLocalHashCode & (len - 1);
//不在同一个位置
if (h != i) {
//老位置的entry置为null
tab[i] = null;
// Unlike Knuth 6.4 Algorithm R, we must scan until
// null because multiple entries could have been stale.
//从h开始往后遍历找到entry为空终止遍历,执行插入操作
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}