jdk ThreadLocal - 969251639/study GitHub Wiki
ThreadLocal的实例代表了一个线程局部的变量,每条线程都只能看到自己的值,并不会意识到其它的线程中也存在该变量。
它采用采用空间来换取时间的方式,解决多线程中相同变量的访问冲突问题。
它最常用的几个方法是set,get,remove
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);
}
获取当前线程,从当前线程中取出ThreadLocalMap,存在则将变量作为value,自己作为key put到ThreadLocalMap中,不存在则创建ThreadLocalMap后将自己作为key set到ThreadLocalMap中
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
public class Thread implements Runnable {
...
ThreadLocal.ThreadLocalMap threadLocals = null;
...
}
可以看到每隔Thread实例都保存ThreadLocal.ThreadLocalMap变量作为成员变量,这样一来每个线程都有自己的Map来保存自己的变量
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
ThreadLocalMap是ThreadLocal静态内部类,并且有一个设置key和value的构造方法
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);
}
可以看到直接将ThreadLocal做为key,算出映射表位置,然后设置到map中,最后还设置了负载因子,用于计算扩容
另外ThreadLocalMap存放数据的Entry类也是一个ThreadLocalMap的内部类
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
它是一个弱引用的类,那么当jvm gc时,它的key是会被垃圾回收器回收掉的,所以建议还是将ThreadLocal声明为static,当然这样做的一个好处便是当ThreadLocacl的实例被回收后,也不会发生内存泄露,因为ThreadLocal作为key是弱引用,在下次gc时也是可以被回收
当然ThreadLocal也依旧有内存泄露的风险,就是当线程一直在运行着,且key在gc时被回收,而ThreadLocal实例的生命周期也是比较短,那么就有可能造成该线程的ThreadLocalMap的key为null,value为之前存放的内容,即有这么的一行代码存在ThreadLocalMap.set(null, Object);最终导致value对象没有被回收
所以还是将ThreadLocal声明为static
那么为了防止key为null的情况,就需要在指定场景调用它的remove方法
remove:
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
private void remove(ThreadLocal<?> key) {
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.get() == key) {//找到后清除
e.clear();
expungeStaleEntry(i);
return;
}
}
}
public void clear() {
this.referent = null;
}
再回到set方法中,当当前线程存在ThreadLocalMap时直接调用了ThreadLocalMap的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();
}
也是比较简单,根据hash计算的出位置,如果存在冲突则在链表中找是否已经存在该value,存在则覆盖,另外,这里也会清除key为null的value,如果没有则设置到制定位置,最后计算是否需要扩容
get:
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();
}
get方法也很简单,就是从ThreadLocalMap的映射表中找,找到返回相应的value,否则调用setInitialValue返回初始值,也就是null
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;
}