一、样例及原理
// 成员变量
ThreadLocal
【多线程工具ThreadLocal】
文章图片
ThreadLocal以一种空间换时间的思想(变量在不同的线程开辟副本),解决并发问题。
线程持有名为threadLocals的引用,指向一个ThreadLocalMap
- ThreadLocalMap的本质是一个Entry对象数组
如:hash取余计算出落点桶是5,但位置5已经有其它entry,那么会尝试放入桶6……
- key是ThreadLocal对象本身,由Entry对象以弱引用的方式指向key
如果持有ThreadLocal的对象被回收了(样例中的成员变量不存在了),意味着指向ThreadLocalMap的key的强引用不存在了,那么弱引用被GC扫描到时也会被回收。
- value则是要存储的对象
public void set(T value) {
Thread t = Thread.currentThread();
// 获取线程的threadLocals变量
ThreadLocalMap map = getMap(t);
if (map != null)
// == 2.找到Entry数组中的entry,并赋值
map.set(this, value);
else
// == 1.创建ThreadLocalMap,并赋值
// - 线程有个threadLocals变量,这个变量指向Entry数组(一个Thread关联的多个ThreadLocal对象,默认16);
//- Entry对象是弱引用的
createMap(t, value);
}
1.创建ThreadLocalMap
java.lang.ThreadLocal#createMap
void createMap(Thread t, T firstValue) {
// ## 调用ThreadLocalMap的构造函数,将当前的threadLocal作为key
// 最终赋值给线程的threadLocals变量
t.threadLocals = new ThreadLocalMap(this, firstValue);
}// ThreadLocalMap的构造函数
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;
// 扩展因子,size * 2/3
setThreshold(INITIAL_CAPACITY);
}
关键类、属性
# Thread类
ThreadLocal.ThreadLocalMap threadLocals = null;
# ThreadLocal类
static class ThreadLocalMap {private Entry[] table;
// table的size,也就是本线程对应的ThreadLocal数量
private int size = 0;
// 弱引用:一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存// 如果不使用弱引用,那么当持有value的强引用释放掉后,当线程没有回收释放时,
// threadLocalMap会一直持有ThreadLocal以及value的强应用,导致value不能够被回收,从而造成内存泄漏。
static class Entry extends WeakReference> {
Object value;
Entry(ThreadLocal> k, Object v) {
super(k);
value = https://www.it610.com/article/v;
}
}
}
2.ThreadLocalMap#set
private void set(ThreadLocal> key, Object value) {
Entry[] tab = table;
int len = tab.length;
// 根据hash值和len找落点
int i = key.threadLocalHashCode & (len-1);
// 线性查找
for (Entry e = tab[i];
e != null;
// 循环中做线性查找,落点i在数组中移动(如果已经是数组的最后一个位置,会从位置0继续查找)
e = tab[i = nextIndex(i, len)]) {// 获取当前位置的key->ThreadLocal
ThreadLocal> k = e.get();
// == 1.1、Entry数组中找到了对应的ThreadLocal,赋值替换
if (k == key) {
e.value = https://www.it610.com/article/value;
return;
}// ## 2、原位置的entry为空(stale-失效),替换
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}// == 1.2、Entry数组中没找到,新建Entry,放入空槽i(经历上面的循环后,i为最近的空位)位置
tab[i] = new Entry(key, value);
int sz = ++size;
// -- a、满足扩容条件(条件:无法清理 && 达到阈值),做扩容操作
if (!cleanSomeSlots(i, sz) && sz>= threshold)
// -- b、扩容
rehash();
}
a、桶清理
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];
// entry不为空,但entry的key为空(## 弱引用被回收,前提条件是持有ThreadLocal的对象被回收,见下图)
if (e != null && e.get() == null) {
n = len;
// 执行清理操作,返回值设置为true
removed = true;
// == 清理无效entry
i = expungeStaleEntry(i);
}
}
// 通过size(实际的Entry对象个数,也就是线程持有的ThreadLocal个数)二进制右移来确定循环次数
// 举例:2->0循环2次;8->0循环4次
while ( (n >>>= 1) != 0);
return removed;
}
看下实际的清理方法
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// 清楚当前的无效节点
tab[staleSlot].value = https://www.it610.com/article/null;
tab[staleSlot] = null;
size--;
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 = https://www.it610.com/article/null;
tab[i] = null;
size--;
} // -- 帮助k找到实际的桶
// 原来在i位置,但当年选择i位置是无奈之举——hash冲突,实际是h位置;
// 现在有机会把它落在该落的h位置,i位置清空
else {
int h = k.threadLocalHashCode & (len - 1);
if (h != i) {
tab[i] = null;
// 好吧,实际落点h也被占用了,只能继续找到新的h位
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}
b、rehash()
private void rehash() {
// 实际的清理方法,已经分析过
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
// 扩容
resize();
}
## 扩容 && 旧桶对象迁新桶
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
// 2倍扩容
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 = https://www.it610.com/article/null;
// Help the GC
} else {
// 计算落点
int h = k.threadLocalHashCode & (newLen - 1);
// hash冲突,找最近空位
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
}
}
}setThreshold(newLen);
size = count;
table = newTab;
}
原位置的entry为空(stale-失效),替换
private void replaceStaleEntry(ThreadLocal> key, Object value,
int staleSlot) {
Entry[] tab = table;
int len = tab.length;
Entry e;
// 往左查找一波(与其它方向相反,按我的理解作更全面的清理)
int slotToExpunge = staleSlot;
for (int i = prevIndex(staleSlot, len);
(e = tab[i]) != null;
i = prevIndex(i, len))
if (e.get() == null)
slotToExpunge = i;
// 其它不分析了(懒):看上去都是调用前面的各种已分析过的方法,总之就是确保扫描的全面
for (int i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal> k = e.get();
if (k == key) {
e.value = https://www.it610.com/article/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 (k == 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);
}
三、get()
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
// == 获取entry节点。从set的逻辑推断——肯定有在Entry环上查找的逻辑
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}java.lang.ThreadLocal.ThreadLocalMap#getEntry
private Entry getEntry(ThreadLocal> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
// -- 找到直接返回
if (e != null && e.get() == key)
return e;
// -- 找不到,作线性查找
else
return getEntryAfterMiss(key, i, e);
}java.lang.ThreadLocal.ThreadLocalMap#getEntryAfterMiss
private Entry getEntryAfterMiss(ThreadLocal> key, int i, Entry e) {
Entry[] tab = table;
int len = tab.length;
while (e != null) {
ThreadLocal> k = e.get();
if (k == key)
return e;
// 帮助清理
if (k == null)
expungeStaleEntry(i);
// 线性查找
else
i = nextIndex(i, len);
e = tab[i];
}
return null;
}