ThreadLocal通俗說法:執行緒的本地變數,通過為每個執行緒建立副本的方式解決執行緒隔離問題,實現執行緒中的變數傳遞
比如:
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;
}
}
private Entry[] table;
// 初始化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;
setThreshold(INITIAL_CAPACITY);
}
}
public T get();
public void set(T value);
public void remove();
protected T initialValue();
預設的initialValue是返回null,你也可以在建立ThreadLocal變數的時候重寫該函數。
// 預設的
protected T initialValue() {
return null;
}
// 重寫initialValue函數的實現
private static final ThreadLocal<Map<Charset, CharsetDecoder>> decoders =
new ThreadLocal<Map<Charset, CharsetDecoder>>()
{
@Override
protected Map<Charset, CharsetDecoder> initialValue()
{
return new IdentityHashMap<>();
}
};
首先獲取當前的執行緒,然後獲取當前執行緒的threadLocals,也就是執行緒獨佔變數,通過map.getEntry(this)獲取Entry,這裡的this代表一個ThreadLocal物件,即entry的key,返回這個entry的value。
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
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();
}
這個同get,不解釋了
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
ThreadLocalMap的key ThreadLocal是弱參照的原因: