ThreadLocalMap
ThreadLocalMap 是 ThreadLocal 静态内部类,每个 Thread 都会有一个 ThreadLocalMap
java
static class ThreadLocalMap {
// 哈希表存储数组
private Entry[] table;
// 数组初始容量 16
private static final int INITIAL_CAPACITY = 16;
// 元素数量
private int size = 0;
// 扩容阈值:容量2/3
private int threshold;
// Entry:弱引用包裹ThreadLocal
static class Entry extends WeakReference<ThreadLocal<?>> {
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k); // key弱引用
value = v;
}
}
}
构造方法
java
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
// 计算hash下标:threadLocalHashCode & (len-1)
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
get
java
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
T result = (T)e.value;
return result;
}
}
// map为空 / entry为空,返回初始值
return setInitialValue();
}
getEntry
java
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
// 冲突/过期key,线性探测查找
return getEntryAfterMiss(key, i, e);
}
setInitialValue
java
private T setInitialValue() {
// 子类重写initialValue提供默认值,默认null
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
// 调用 ThreadLocalMap 的构造方法,创建 map
createMap(t, value);
return value;
}
createMap
java
void createMap(Thread t, T firstValue) {
// new ThreadLocalMap,第一个Entry key=this(当前tl对象)
t.threadLocals = new ThreadLocalMap(this, firstValue);
}