ThreadLocal 为线程提供一个线程安全的存储空间,只有该线程能够访问。
实际上ThreadLocal其中并不存储数据,而是作为key,存储到Thread自带的ThreadLocal Map中。
ThreadLocal的使用方法非常简单,在一个线程中声明出一个ThreadLocal变量便可以使用。
下面的源码展示出ThreadLocal的基本使用
package org.eventime.juc;
/**
* @author eventime
* ThreadLocal 演示代码
*/
public class threadlocaltest {
public static ThreadLocal[] record = new ThreadLocal[2];
public static void main(String[] args) {
ThreadLocal<String> test = new ThreadLocal<>();
test.set("test");
ThreadLocal<String> test2 = new ThreadLocal<>();
test2.set("test2");
record[0] = test;
record[1] = test2;
fun1();
fun2();
fun3();
fun4();
test.remove();
test2.remove();
}
static void fun1() {
System.out.println(record[0].get());
}
static void fun2() {
System.out.println(record[0].get());
}
static void fun3() {
System.out.println(record[0].get());
}
static void fun4() {
System.out.println(record[0].get());
}
}
ThreadLocal一共只暴露出了,五个public方法,我们首先研究一下这五个方法的作用。

查看赋值的函数,可以看到在赋值的时候,ThreadLocal会先获取当前的线程,然后获取一个ThreadLocalMap 类型的map,如果map不为空,那么直接将 this(ThreadLocal对象)和value存入进去。
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
map.set(this, value);
} else {
createMap(t, value);
}
}
每一个Thread都会有一个字段使用ThreadLocalMap存储ThreadLocal变量。
ThreadLocal本身并不直接存储变量,而是作为 key放到map中。
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
在get()方法中,可以看到和set方法相反的过程,从Thread自带的map中返回一个Entry并将其中的value返回。Entry是Map中存储的单位,后面会仔细讲解其中的构造。
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;
}
}
// TODO 这里作用看上去仅仅是返回空值
return setInitialValue();
}
新建一个ThreadLocalMap并放入新值
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
新建一个ThreadLocalMap,传入的firstKey为ThreadLocal变量,值为Object类型。
在第一次创建的时候,会新建一个16大小的Entry数组。
然后通过key的哈希算法确定存储的位置,最后将键值对存入,map的size 大于 1,并将阈值设置为初始值16.
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
Entry 继承自WeakReference,表明这是一个弱引用的数组,键值对在存储的时候,将ThreadLocal变量存储到k,将value存储到普通的Object中去。
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
下面让我们着重分析一下 ThreadLocalMap中的方法,需要注意的是ThreadLocalMap字段不会暴露出去。
ThreadLocalMap一共只有4个字段,核心为Entry数组。
static class 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
}
在第一个构造函数中,接受一个(key,value)。然后初始化Entry数组,初始数量为16。
然后根据key的hashcode以及当前的容量去计算index的位置。后续将Entry数组大小设置为1,一般设置当前阈值为 2/3(向下取整)。
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
核心set函数:接受一个(key,value)键值对,然后获取Entry数组,以及当前数组的长度,根据key以及数组长度计算出index。
当遇到碰撞的时候,ThreadLocalMap采用的方法是,先判断这个位置是不是key,如果是将其值更新。如果指向null,那么新建键值对并且将其放入该位置。最后将无效的值清理后,无效值只会清理log(size)的范围。然后去判断其中的元素数量是否超过了阈值,如果超过阈值那么重新rehash一遍。
向后寻找一个空的位置。在寻找到这个空位置的时候。
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)]) {
if (e.refersTo(key)) {
e.value = value;
return;
}
if (e.refersTo(null)) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
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);
}
/**
* Decrement i modulo len.
*/
private static int prevIndex(int i, int len) {
return ((i - 1 >= 0) ? i - 1 : len - 1);
}
ThreadlocalMap的resize函数,resize函数将现有的Entry数组长度乘2并再次分配全部的键值对。
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
int newLen = oldLen * 2;
Entry[] newTab = new Entry[newLen];
int count = 0;
for (Entry e : oldTab) {
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;
}
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.refersTo(null)) {
n = len;
removed = true;
i = expungeStaleEntry(i);
}
} while ( (n >>>= 1) != 0);
return removed;
}
ThreadLocalMap是如何解决哈希碰撞问题的?
尽管ThreadLocalMap采用的哈希算法已经尽可能生成均匀的哈希值,但是由于数组大小的限制,碰撞在所难免。本节探究一下,ThreadLocalMap如何解决哈希碰撞问题。上文已经讲解过,ThreadLocal会优先选择当前Hash值所在的位置,如果为null,则新建Entry放入该位置。如果该位置指向key的时候直接更新值,如果当前位置指向null,说明该位置的ThreadLocal已经被GC,那么直接替代。如果当前位置并不满足为null或者指向key,那么继续向后寻找这样的位置。
/**
* 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) {
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.refersTo(key)) {
e.value = value;
return;
}
if (e.refersTo(null)) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
在将值放入了table之后,会执行 “清理一些槽”的操作,如果清理失败并且当前table内存储的Entry数量超过threashold执行 rehash();
cleanSomeSlots 函数接受两个参数,一个i表示一个当前有效的位置,因为在set()函数中,我们在i的位置放入了一个有效的键值对。n表示当前键值对的数量。
在执行cleanSomeSlots的时候,会从 i + 1的位置开始,去尝试 “清理无效的键值对”,如果一个位置不为null但是key却指向了 null,那么判定该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.refersTo(null)) {
n = len;
removed = true;
i = expungeStaleEntry(i);
}
} while ( (n >>>= 1) != 0);
return removed;
}
清理无效值的时候,先将当前确定的无效值设置为 null,然后对该位置后的各个Entry进行rehash操作,直到找到一个空的槽。因为这些值可能是发生hash碰撞才向后寻找位置放入,所以当清理了在他前面无效的Entry之后,原本被占用的位置空了出来,此时该Entry可以去尝试放入。
这样操作可以减少单次get()查找table的次数。最终返回一个无效Entry后的第一个为null的位置。
/**
* 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).
*/
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 {
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;
}
如果上面操作执行完毕后,table中的Entry数量仍然高于阈值,那么便要执行rehash操作。在上面 cleanSomeSlots操作中清理了 “一些”无效的位置。在清理过后仍然高于阈值,此时先去调用expungeStaleEntries()去尝试清理所有的无效Entry。清理完毕后,如果此时所包含的有效Entry数量大于threshold的3/4,那么此时执行扩容操作。
private void rehash() {
expungeStaleEntries();
// 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.refersTo(null))
expungeStaleEntry(j);
}
}
扩容操作
将table的长度扩大2倍,将旧table中的内容放入新table,取hash方法依旧为 k.threadLocalHashCode & (newLen - 1)。 k.threadLocalHashCode在ThreadLocal对象创建的时候便确定下来不再改变,而取低位数量的多少确定在表中的位置。
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
int newLen = oldLen * 2;
Entry[] newTab = new Entry[newLen];
int count = 0;
for (Entry e : oldTab) {
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函数中,我们提到,当发现此位置的key指向null,我们会替代为当前值。
如果table中本来就存在该Entry怎么办?在更新逻辑中,会首先从无效entry位置向前探测,直到为null,获取slotToExpunge。随后向后探测并更新slotToExpunge,如果找到存在的Entry值,那么将其与无效无效entry交换。如果一直没有找到那么将其放入到为null的位置。在返回之前总是会根据slotToExpunge去清理无效值。
/**
* 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).
int slotToExpunge = staleSlot;
for (int i = prevIndex(staleSlot, len);
(e = tab[i]) != null;
i = prevIndex(i, len))
if (e.refersTo(null))
slotToExpunge = i;
// 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)) {
// 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 (e.refersTo(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 (e.refersTo(null) && slotToExpunge == staleSlot)
slotToExpunge = i;
}
// If key not found, put new entry in stale slot
tab[staleSlot].value = null;
tab[staleSlot] = new Entry(key, value);
// If there are any other stale entries in run, expunge them
if (slotToExpunge != staleSlot)
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
ThreadLocal get()
get的逻辑比较简单,在取hash后发现不是想取的Entry时会向后探测,在遇到无效Entry的时候,变换执行删除无效Entry的逻辑。
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;
}
}
return setInitialValue();
}
private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
if (e != null && e.refersTo(key))
return e;
else
return getEntryAfterMiss(key, i, e);
}
private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
Entry[] tab = table;
int len = tab.length;
while (e != null) {
if (e.refersTo(key))
return e;
if (e.refersTo(null))
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
参考资料:

9566

被折叠的 条评论
为什么被折叠?



