原理
每个Thread实例会有自己的ThreadLocalMap实例,ThreadLocal的set(value)方法会获取当前线程,把value存储到线程自己的ThreadLocalMap中,也就实现了线程之间的隔离:每次涉及到ThreadLocal的操作,实际上都是线程在操作自己的副本,线程之间不会共享ThreadLocal实例中的value值。所以ThreadLocal适用于在多线程环境,变量需要在线程间隔离,在方法间被使用的场景。
使用
例如SpringMVC中,controller是单例的,controller中注入的HttpServletRequest,当并发请求到来时,request中携带的信息是不同的,spring就是使用了ThreadLocal对request进行线程隔离。
实现过程是每一个请求都会先从RequestContextFilter中过来,执行里面的initContextHolders(request, attributes),它会把每个请求的request和response放ThreadLocal里,而注入的的httpServletRequest 就是从ThreadLocal里面取。
源码分析
private final int threadLocalHashCode = nextHashCode();
private static AtomicInteger nextHashCode =
new AtomicInteger();
private static final int HASH_INCREMENT = 0x61c88647;
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
ThreadLocal有一个哈希值threadLocalHashCode,该值用来快速锁定value在ThreadLocalMap的存储位置。
HASH_INCREMENT是一个比较特殊的值,哈希值为该值的倍数时分布较为分散,存储时避免哈希碰撞。
nextHashCode为static类型,所有线程中的ThreadLocal在创建时使用nextHashCode方法在nextHashCode上递增,所以该变量需要同步,使用了原子类型。
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
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);
}
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 T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
protected T initialValue() {
return null;
}
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
通过createMap方法可以看到每个Thread实例对象会有一个ThreadLocalMap实例,
存和取操作较为简单,都是先获取当前线程,然后操作ThreadLocalMap即可。
下面看ThreadLocalMap的实现。
static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal<?>> {
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
private Entry[] table;
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)]) {
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();
}
Entity数组是用来存储set到ThreadLocal的value的数据结构。
int i = key.threadLocalHashCode & (len-1)
Entry的长度必须为
2
n
2^n
2n ,这样len-1的值的二进制表示的有效位全为1,再与threadLocalHashCode进行按为与操作,即可得到一个[0,len)的值,使用该值作为下标插入Entry数组,可以大大降低碰撞概率。
Entrty继承了WeakReference,当ThreadLocal对象未被垃圾回收时,可以通过entry.get()返回对应的ThreadLocal对象。而一旦ThreadLocal对象被垃圾回收,再通过entry.get()返回只能得到null。这一点是为了防止线程结束后,ThreadLocal对象被Entry的key引用,无法被垃圾回收而导致内存泄漏。不过,仅仅使用了弱引用还是不够的,因为Entry还有对value的引用,这一点需要通过将失效的Entry的value置空来解决,之后的代码会提到。
可以看到,在计算出下标进行插入时,如果key相同,那么覆盖为新的value,如果key为空,说明此处之前的ThreadLocal已经被垃圾回收了。从for循环之后的代码可以看出,如果下标对应的位置已经被使用(不为null),则往后顺延。所以在set时,遇到key为null,如果不是第一次set,那么该ThreadLocal对应的Entry会被set到下标之后的某个位置,需要将他更新到当前下标位置,以方便之后的读取。所以使用到replaceStaleEntry方法。
下面看replaceStaleEntry源码:
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).
//向前查找到最近的一个需要清除的Entry,
//因为每次进行清除会从staleSlot下标位置开始,逐个检查之后的一片连续的Entry,直到遇到null。
//这样做,可以防止如果staleSlot之前的连续元素存在需要清除的Entry,staleSlot之后的连续元素被重复扫描。
//即向前移动扫描清除开始的位置,将他们一次扫描清除。
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
//检查staleSlot之后的连续元素是否存在ThreadLocal对应的key
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.
//如果存在需要更新到当前staleSlot位置
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.
//如果staleSlot之后的连续元素中也有失效的Entry(对应的ThreadLocal被回收),
//且staleSlot之前的连续元素不存在需要被清除的entry,那么更新扫描清除开始位置
if (k == null && slotToExpunge == staleSlot)
slotToExpunge = i;
}
// If key not found, put new entry in stale slot
//扫描完连续元素,未发现key,那么在staleSlot下标位置设置entry即可
tab[staleSlot].value = null;
tab[staleSlot] = new Entry(key, value);
// If there are any other stale entries in run, expunge them
//如果扫描清除点不是staleSlot,说明连续元素中有被回收的ThreadLocal,需要从该位置开始进行扫描清除
if (slotToExpunge != staleSlot)
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
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;
//扫描之后的连续元素,遇null停止
for (i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
//key为空表面对应的ThreadLocal已经被垃圾回收,那么这个节点可以释放
if (k == null) {
e.value = null;
tab[i] = null;
size--;
} else {
//如果不为null,计算下标位置,看看是否需要更新位置。因为在set时可能存在哈希碰撞,导致存储位置被往后顺延,而一段时间后之前 被占用的位置被垃圾回收了。这时更新位置方便查找。
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;
}
//在进行清除时不光扫描某个位置开始的连续元素,对于之后的空间也会进行检查,
//但是这片空间可能会很大,如果也进行逐个扫描,那么每次清除的时间复杂度都是n,
//可以看到源码中的优化方法是只进行log(2,n)次,n为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;
i = expungeStaleEntry(i);
}
} while ( (n >>>= 1) != 0);
return removed;
}
以上就是ThreadLocal是如何做到防止内存泄漏的。