ThreadLocal是多线程间并发访问的一种解决方案,只适合共享不同的对象,如果保存多线程间共享的对象则不能保证同步。
注意:不能将同一个对象在不同线程中,保存到ThreadLocal中。
原理的代码分析:
ThreadLocal在每个线程的第一次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 getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);//每个线程第一次初始化map的地方。
}
在set方法中,通过当前线程获取ThreadLocalMap对象。所以保存数据的ThreadLocalMap对象实际上是当前线程对象的一个属性:
publicclass Thread implements Runnable{ThreadLocal.ThreadLocalMap threadLocals = null;}。
在初始化map的时候(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 firstKey为多线程间共享的ThreadLocal对象的引用,Object firstValue为需要保存的数据对象。对一个ThreadLocal对象,threadLocalHashCode是final的,唯一的,所以 table的下标i 无论在单个线程还是多个线程都是唯一的。所以,对每个线程,一个ThreadLocal对象只能保存一个Object firstValue,重复set()会覆盖。
我们再来看这个ThreadLocalMap类的内部类Entry:
static class Entry extends WeakReference<ThreadLocal> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal k, Object v) {
super(k);
value = v;
}
}
public class WeakReference<T> extends Reference<T>{
public WeakReference(T referent) {
super(referent);
}
}
public abstract class Reference {private T referent; /* Treated specially by GC */ }
可知,多线程间共享的ThreadLocal firstKey对象被保存在抽象类Reference中。而Object firstValue被保存在ThreadLocalMap类的内部类Entry中。
另一方面,get数据时:
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();
}
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);
}
先通过线程对象,获取保存在线程对象中的Map,在通过共享的ThreadLocal对象引用获取保存的对象Value,如:if (e != null && e.get() == key) return e; 。
总结:
实际上,ThreadLocal对象并没有保存线程要保存的对象,而是线程对象本身保存了共享的ThreadLocal对象引用和要保存的对象Value。
ThreadLocal对象类似一个包装类,调用其中的方法,以线程对象为查询条件,找到线程属性中保存数据的Map对象ThreadLocalMap,再已共享的ThreadLocal对象引用,在Map中找到线程保存的值。
遗留问题:为什么ThreadLocal不提供ThreadLocalMap getMap(Thread t)的public方法,如果提供的话,我们就可以在线程结束后通过共享的ThreadLocal,提取各个线程保存的对象了。现在只有包访问域,我们就只能在线程内部访问它了。
看是否理解了,看问题:
1、每个线程的变量副本是存储在哪里的?
2、变量副本是怎么从共享的那个变量赋值出来的?源码中的threadlocal的初始值是什么时机设置的?