ThreadLocal源码
ThreadLocal<String> threadLocal =new ThreadLocal<String>();
当ThreadLocal set东西的时候首先找到当前线程指向的一个map(ThreadlocalMap:ThreadLocalMap其实就是ThreadLocal的一个静态内部类,里面定义了一个Entry来保存数据,而且还是继承的弱引用。在Entry内部使用ThreadLocal作为key,使用我们设置的value作为value。)
ThreadLocal最为重要的两个方法,get、set。
①:ThradLocal的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);
}
这里的Thread.currentThread就是获取到当前前程。通过ThreadLocalMap的getMap方法试图去获取是否已经有t对象所对应的map。
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
ThreadLocal.ThreadLocalMap threadLocals = null;
如果map非空的话就把ThreadLocal的对象和要放入的值set到Map中具体代码如下所示:
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();
}
如果map的值为null就执行createMap
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);
}
②ThreadLocal的get方法
也是先拿到当前线程,去ThreadLocalMap中去尝试是否能够拿到map如果map不为空的话就通过对象去获得ThreadLocalMap中的Entry的value。如果map为空就执行setInitialValue()方法
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
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;
}
重要!!!
static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal k, Object v) {
super(k);
value = v;
}
}
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread()); //先获取ThreadLocalMap对象实例
if (m != null) //直接通过threadLocal实例删除value值
m.remove(this);
}
因为entry继承了弱引用。回收垃圾机制看到之后就会回收,这样一来就容易照成entry中key已经消失但是key所对应的value还保存在entry中,这里用完之后一定remove掉整个entry