该提前分析的都分析完了,现在,来看一下ThreadLocal,本来还想还顺带学习一下Netty封装的FastThreadLocal,但是写的有点多了,后面抽时间再写一篇了
What
ThreadLocal
也是日常开发中比较常用的,他的注视就很好的诠释了他是干什么用的。简单的说,ThreadLocal
可以看作线程的私有变量。需要注意的是,他并不是用来处理共享变量的,下面会进行分析
/*This class provides thread-local variables. These variables differ from
their normal counterparts in that each thread that accesses one (via its
{@code get} or {@code set} method) has its own, independently initialized
copy of the variable. {@code ThreadLocal} instances are typically private
static fields in classes that wish to associate state with a thread (e.g.,
a user ID or Transaction ID).
...略
*/
/**
这个类提供线程局部变量。 这些变量与其正常的对应方式不同,因为访问一个的每个线程(通过其get或set方法)都有自己独立初始化的变量副本。 ThreadLocal实例通常是希望将状态与线程关联的类中的私有静态字段(例如,用户ID或事务ID)。
*/
Details
createMap
简单将一下下源码,当调用set()
方法塞值的时候呢,会创建ThreadLocalMap
并赋值给线程的threadLocals
,ThreadLocalMap
内部实现是通过Entry
数组,通过哈希算出位置,Entry
本身继承弱引用,key封装为弱引用,value则是强引用。
所以理论上key
删了,value引用还在
public void set(T value) {
//获取当前线程
Thread t = Thread.currentThread();
//获取ThreadLocalMap 1.1
ThreadLocalMap map = getMap(t);
if (map != null)
//塞值,ThreadLocal作为key
map.set(this, value);
else
//创建map1.2
createMap(t, value);
}
//1.1
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
//1.2
void createMap(Thread t, T firstValue) {
//2.1
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
//2.1ThreadLocalMap构造方法
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
//创建Entry数组
table = new Entry[INITIAL_CAPACITY];
//位运算算出放在哪
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
//塞值 2.2
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
//2.2
static class Entry extends WeakReference<ThreadLocal<?>> {
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
## set
这一段承接上面的set方法,分开成两个部分,单独讲一下,上面看到了,ThreadLocalMap
是一个Entry
数组,它没有像HashMap
数组+链表/红黑树的一个结构,他是通过hash运算算出来要放在哪,那么如果你线程中运用了很多ThreadLocal
,那么肯定会遇到坑位被占的情况,既然是数组,也就只能向后顺延,找到null的位置,但是前面提到了,弱引用的问题,前面一篇,分析了会被GC回收的问题,那么key就是null,但是value的引用还是在的,这种应该要怎么处理,就是觉得这部分太多,特地和上面分开来。
private void set(ThreadLocal<?> key, Object value) {
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
//遍历下一个entry为null的情况
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
//便利是从i依次向后便利,如果有相等的情况就直接赋值了
if (k == key) {
e.value = value;
return;
}
//key被GC回收的情况
if (k == null) {
//1.1
replaceStaleEntry(key, value, i);
return;
}
}
//直到遍历到数组中的null的情况
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
//1.2
rehash();
}
//1.1
/**
* key:我们传进来的ThreadLocal
* value:我们穿进来的value
* staleSlot:外层循环中数组角标,不会变!
* 这个位置的entry的key已经被GC回收了
*/
private void replaceStaleEntry(ThreadLocal<?> key, Object value,
int staleSlot) {
Entry[] tab = table;
int len = tab.length;
Entry e;
//slotToExpunge清除起始位置的意思
int slotToExpunge = staleSlot;
//直接从staleSlot的前一个位置开始
//这一段就是找到前一个entry为null的位置停,slotToExpunge记录最开始已经失效的entry的下标
for (int i = prevIndex(staleSlot, len);
(e = tab[i]) != null;
i = prevIndex(i, len))
if (e.get() == null)
slotToExpunge = i;
//从staleSlot的后一个位置开始
for (int i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
//如果key相等,说明,当前位置的entry未失效,staleSlot位置的entry失效,可能是前面槽位不够放过来的,或者是hash碰撞占了这个位置的,实际我们的真正的entry由于hash碰撞放在了后面,此时就是交换
//将staleSlot位置失效的entry放到i当前位置,将我们完好的entry拿过来
if (k == key) {
e.value = value;
tab[i] = tab[staleSlot];
tab[staleSlot] = e;
// 如果最开始过期的位置就是staleSlot位置,此时已经被置换到i位置,就是从i位置开始清理
if (slotToExpunge == staleSlot)
slotToExpunge = i;
//从slotToExpunge位置开始清除entry
//2.1,2.2
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
return;
}
//清理staleSlot位置
if (k == null && slotToExpunge == staleSlot)
slotToExpunge = i;
}
// 清除
tab[staleSlot].value = null;
tab[staleSlot] = new Entry(key, value);
// 清除
if (slotToExpunge != staleSlot)
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
//2.1
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// 主要就是清除引用,等GC可以清除
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,如果扩容,可能不在这个位置上,不在这个位置就清除,放到扩容后的位置上
int h = k.threadLocalHashCode & (len - 1);
if (h != i) {
tab[i] = null;
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}
/**
2.2
* i:数组中,staleSlot位置后的null的位置
*/
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;
//就是上面那个2.1
i = expungeStaleEntry(i);
}
} while ( (n >>>= 1) != 0);
return removed;
}
中场休息队上面添加key做一个总结
- 如果找到同样的key,直接替换
如果entry过期,key为null(这里为了方便记录当前过期位置为X)
- 如果实际匹配的key(记录这个位置为Y),Y移动到x位置,X移动到Y,并从X当前所在位置开始清理过期entry
- 如果到下一个null的entry位置为止,没有找到对应的key,就把要塞的值塞在x位置,并开始清理过期entry(这里有多重情况,看主食)
- 如果直接找到null位置,就直接塞值
既然是个数组,那么久肯定会有扩容问题,也是差不多一样的,到达某一阀值久开始扩容,既然扩容,HashMap
同一位置上哈希值相同,要么再原位,要么再另外一个位置,移过去,继续组成链表完事,这里呢,是算出新位置,从那个位置向后找空位,就不过多赘述了,看下注释吧^_^
//1.2,懒得讲了,也没hashmap复杂,就是清理下过期的entry,塞到新位置
//重新hash
private void rehash() {
//3.1
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
//3.2
resize();
}
//3.1
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)
//上面2.1
expungeStaleEntry(j);
}
}
//3.2
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;
}
get
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
//1.1
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
//1.1
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
//2.1
return getEntryAfterMiss(key, i, e);
}
//2.1
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)
//上面2.1
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab[i];
}
//找不到返回空
return null;
}
Why
为啥Entry继承自WeakReference
在stackoverflow上找到了这个回答。这里就不要脸的贴过来了。(可以过去点个赞)
想象一下。您在程序中使用线程池。为避免并发错误,您经常使用 ThreadLocal。当一个线程完成任务时,你希望 GC 释放 ThreadLocal 对象。因此,在您的线程中将其设置为 null 。
好的。现在有两种情况。A和B。
A:假设ThreadLocalMap中有对ThreadLocal的强引用。ThreadLocal 对象不会被回收。我们必须等到线程对象被回收后才能回收ThreadLocal对象。然而,坏消息是线程池经常重用已经创建的 Thread 对象,而不是在线程完成其任务后回收它们。结果,我们有越来越多的 ThreadLocal 对象无法回收,直到 JVM 没有更多可用内存并抛出 OutOfMemoryError,我们的程序崩溃。
B:因为Entry继承了WeakReference,所以TreadLocalMap中对ThreadLocal对象的引用是弱引用。当线程完成任务时,我们将线程中ThreadLocal的引用设置为null。此时,ThreadLocal对象在ThreadLocalMap中只有一个弱引用。当GC扫描ThreadLocal对象,发现只有一个弱引用时,就忽略弱引用,回收ThreadLocal对象。这就是我们想要的。这就是 Entry 扩展 WeakReference 的原因。
OOM问题
频繁set
get
是会清除无效entry的,但是,如果线程生命周期很长,就会回关了,此时key=null,value一直有引用,清除不掉。一直占着一块内存,容易发生OOM
一直占用着引用的小demo。所以啊,多用remove
private static void test1() throws InterruptedException, NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
int size=1000000;
WeakReference<ThreadLocal<Element>>[] list=new WeakReference[size];
for (int i = 0; i < size; i++) {
ThreadLocal<Element> threadLocal=new ThreadLocal<>();
threadLocal.set(new Element(10));
WeakReference<ThreadLocal<Element>> weakReference=new WeakReference<>(threadLocal);
list[i]=weakReference;
}
System.out.println("------");
mustGC();
for (int i = 0; i < size; i++) {
WeakReference<ThreadLocal<Element>> weakReference=list[i];
ThreadLocal<Element> threadLocal=weakReference.get();
if(threadLocal!=null){
Element demo=threadLocal.get();
if(demo!=null){
System.out.println(i);
}
}
}
Thread t=Thread.currentThread();
System.out.println();
}
private static void mustGC() throws InterruptedException {
System.gc();
Thread.sleep(1000);
}
other
个人觉得,就是个和线程绑定的变量,比较适合单个服务的&&和线程绑定的变量,比如日志跟踪号,事务等。实际上源码也是这么处理的。
哎,恭喜石头人冠军,太强了,Wings诅咒5年了,该偿还结束了吧
本文由mdnice多平台发布
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。