ThreadLocal的用处
对于每一个ThreadLocal实例对象,每个线程往这个ThreadLocal中读写是线程隔离,互相之间不会影响的。它提供了一种将可变数据通过每个线程有自己的独立副本从而实现线程封闭的机制。
image.pngApi
源码解读
1.从set方法开始,初始化容器
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
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);
}
创建一个ThreadLocalMap对象,放到当前线程里。第一次读这块源码的时候感觉一下子绕不过来。举个例子来说明下。
@Test
public void testThreadLocal(){
ThreadLocal<String> t1 = new ThreadLocal<>();
ThreadLocal<String> t2 = new ThreadLocal<>();
ThreadLocal<String> t3 = new ThreadLocal<>();
t1.set("aaa");
t2.set("bbb");
t3.set("ccc");
}
如上,当一个线程执行这段代码,只会创建一个ThreadLocalMap对象放入当前线程内,然后将t1,t2,t3作为key,对应的值作为value放入ThreadLocalMap对象里。
值的注意的是这里的Entity的key是一个弱引用
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
这样做的意义应该是为了gc,因为如果一个线程一直存在的话,它所占用的key,即ThreadLocal实例对象会一直不会被回收。
2.接下来就是重头戏了,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;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
在这里,可以将tab看成一个首尾相接的圆环,初始化被分成16等份,编号从0-15.
进行set操作的时候,先获取key的hash散列值作为下标开始从圆环上遍历。
先认识两个重要函数
expungeStaleEntry
和cleanSomeSlots
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// staleSlot位置的元素是key为null的entity,也就是弱引用被回收了,这种元素自然要被清理掉的
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
// 清理掉之后,如果后面有连续的不为null的entity,那就要往前挪动,或者还有弱引用被回收的,也要清理
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;
}
expungeStaleEntry
的作用就是清理弱引用被回收的entity以及调整往后连续不为null的entity的位置,如果连续不为null的entity中还有弱引用被回收的,也要清理。
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;
i = expungeStaleEntry(i);
}
} while ( (n >>>= 1) != 0);//个人感觉这个操作还是比较魔性的,称之为启发式扫描。。。
return removed;
}
cleanSomeSlots
启发式扫描清理,自行体会吧。。。
set的第一段代码逻辑如下:从位置i开始遍历圆环
1.entity为null,则直接new复制,启发式扫描,判断是否触发扩容
2.entity不为null,且key不为null,key==当前key,直接替换value
3.entity不为null,但是key为null,就进入弱引用替换逻辑
接下来分析下弱引用替换部分
private void replaceStaleEntry(ThreadLocal<?> key, Object value,
int staleSlot) {
Entry[] tab = table;
int len = tab.length;
Entry e;
//这个主要是向前扫描连续的entity,如果有被回收的弱引用,则记录最前面的下标(表面上看是为了清理被回收的弱引用,实际上我不是十分理解他这么做的目的是什么)
// 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;
//向后扫描连续不为null的entity,如果找到目标key就替换
// 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)) {
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) {
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;
}
//刚开始看的时候会质疑这里,因为有可能存在同样key的entity在后面,但是结合整个清理扫描的过程可以确保不会出现这样的情况。
// 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);
}
1.向前扫描连续不为null的entity,如果有被回收的弱引用,记录最前的那个元素下标slotToExpunge
2.如果向后元素不为null,则向后扫描连续不为null的entity,如果寻到到目标key,则替换位置
3.如果向后元素为null,则当前位置插入新元素
个人感觉这个是比较绕的,也有点抽象,要反复多看几遍,一部分一部分理解,最后串起来。
网友评论