线程本地变量,ThreadLocal 提供了 get 与 set 方法为每个使用该变量的线程都保存有一份独立的副本,因此每个 get 总是返回由当前线程在调用 set 时设置的最新值。我们知道对象如果是有状态的,那么该对象就变得不是线程安全的,保证安全可以加锁,ThreadLocal 提供了另外一种思路,利用空间来避免竞争锁浪费的时间,它为每个线程都创建一个状态的副本,各个线程对状态副本进行修改相互之间不影响,这样也能做到线程安全。
下面这个例子:每个线程都生成一个唯一的局部标识符。第一次调用 ThreadId.get() 时分配,之后再调用不会变化。
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();
}
}
数据引用结构图
ThreadLocal 的基本原理:每个线程内部维护了一个 ThreadLocal.ThreadLocalMap 对象,这个对象内维护了一个数组,数组里维护了多个 Entry(节点),每个节点有 referent(key) 和 value,key 存储的是 ThreadLocal 对象的 WeakReference(弱引用),value 里保存的是真正的数据值 。一个线程初次访问 ThreadLocal 的 get 或者 set 方法,通过此线程找到它内部的 ThreadLocalMap,若 ThreadLocalMap 还未初始化就创建 ThreadLocalMap,ThreadLocalMap 内包含一个初始长度为16的数组来存储 key 和 value,再通过 ThreadLocalMapRef 在 ThreadLocalMap 中找对应的 value。若 set 没有设置过 value,调用 get 获取不到 value时,get 方法内会调用一次 initialValue 方法来设置初始值。
关于弱引用,仅仅是提供一种访问在弱引用状态下对象的途径。GC 执行时,若对象无强引用,会直接回收此对象,弱引用不能豁免GC。
上面的例子是使用 get 方法才初始化值,初始值是在构造 ThreadLocal 时指定的初始化方法 initialValue 中设置的。
/**
* 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();
//获取到当前线程内维护的一个 map
ThreadLocalMap map = getMap(t);
if (map != null) {
//通过 threadLocal 引用获取到 map 中的值
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
//若获取不到 value,执行初始化方法设置初始值
return setInitialValue();
}
/**
* 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;
}
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
/**
* 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() {
//执行创建 ThreadLocal 时指定的 initialValue 方法
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
//若 map 不为空,将 key 和 value 放入到 map 中
map.set(this, value);
else
///若 map 为空,初始化 map
createMap(t, value);
return value;
}
/**
* 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);
}
/**
* 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) {
//INITIAL_CAPACITY 默认为 16
table = new Entry[INITIAL_CAPACITY];
//计算此 key 应该放在数组中的位置
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
//新建一个节点,放到数组中
table[i] = new Entry(firstKey, firstValue);
size = 1;
//设置扩容的阀值
setThreshold(INITIAL_CAPACITY);
}
/**
* The initial capacity -- MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = 16;
/**
* Set the resize threshold to maintain at worst a 2/3 load factor.
*/
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
若执行 set 方法,那么之后的所有 get 都会获取到 set 设置的值。若 hash 冲突,ThreadLocal 采用线性探测法,向数组后面查找为空的槽点作为下标,将数据放入。
/**
* 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();
//一样,也是要先获取到此线程内的 map
ThreadLocalMap map = getMap(t);
if (map != null)
//设置 map 中节点的 value
map.set(this, value);
else
createMap(t, value);
}
/**
* 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);
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;
}
//找下一个,线性探测,直到 e == null 退出循环
}
//此 hash 值没有放入到数组中,重新创建一个节点放入数据
tab[i] = new Entry(key, value);
int sz = ++size;
//放入数据后,清除可能存在的 key 为空,value 不为空的 stale 节点
//若清除了一个或以上节点,不用扩容
//若没有清除且超过数组阀值需要进行扩容
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;
//移除过,就标记为 true
removed = true;
//移除 stale 失效节点
i = expungeStaleEntry(i);
}
} while ( (n >>>= 1) != 0);
return removed;
}
若一个线程创建的 ThreadLocal 对象过多,会触发扩容操作,每次容量增加一倍
/**
* 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() {
//先移除所有的 stale 失效节点
expungeStaleEntries();
//再进行扩容
// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
resize();
}
/**
* 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)
//找到一个就移除一个 stale 节点
expungeStaleEntry(j);
}
}
/**
* 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 {
//重新计算下标
int h = k.threadLocalHashCode & (newLen - 1);
//若有冲突,一直往下找空置的槽点
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
}
}
}
setThreshold(newLen);
size = count;
table = newTab;
}
每次调用 set 方法会移除失效节点,还有一个单独的 remove 方法直接移除节点。
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
/**
* Remove the entry for key.
*/
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;
}
}
}
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// expunge entry at staleSlot
tab[staleSlot].value = 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) {
e.value = null;
tab[i] = null;
size--;
} else {
//注意线性探测方法的缺点,若有一个槽点 hash 冲突,它会向后找一个空闲的位置,
//之后若有节点 key 的 hash 为空闲位置对应的 hash 进数组,此节点不能直接放入,
//也是要向后找,这样导致一连串的冲突
//重新计算 hash,重新维护在链表的位置,尽可能的恢复到节点应该放到的槽点上去
int h = k.threadLocalHashCode & (len - 1);
if (h != i) {
tab[i] = null;
// Unlike Knuth 6.4 Algorithm R, we must scan until
// null because multiple entries could have been stale.
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}
ThreadLocal 计算节点在数组中的下标方式使用了 Fibonacci hashing
int i = key.threadLocalHashCode & (len-1);
threadLocalHashCode 在 ThreadLocal 初始化的时候赋值
private final int threadLocalHashCode = nextHashCode();
/**
* 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);
}
HASH_INCREMENT 是一个特殊值,十六进制 0x61c88647 转换为 int 值为 1640531527。
1640531527 = 黄金分割数(近似为 0.618)* (1<<31),这个数能保证 nextHashCode 均匀分布在 1<<31 内。