public void set(T value) {
Thread t = Thread.currentThread(); //获得当前线程
ThreadLocalMap map = getMap(t); //将当前线程作为参数传入,来获取ThreadLocalMap
if (map != null)
map.set(this,value);
else
createMap(t,value);
}
void createMap(Thread t,T firstValue) {
t.threadLocals = new ThreadLocalMap(this,firstValue); //看到了吧,ThreadLocalMap直接是给Thread保存的
}
ThreadLocalMap(ThreadLocal<?> firstKey,Object firstValue) { //看到参数名字没,firstKey,ThreadLocal传进来是当作key值的!
table = new Entry[INITIAL_CAPACITY]; //table其实是private Entry[] table; 一个数组而已
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey,firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
1 private void set(ThreadLocal<?> key,Object value) {
2
3 Entry[] tab = table;
4 int len = tab.length;
5 int i = key.threadLocalHashCode & (len-1);
6
7 for (Entry e = tab[i];
8 e != null;
9 e = tab[i = nextIndex(i,len)]) {
10 ThreadLocal<?> k = e.get();
11
12 if (k == key) {
13 e.value = value;
14 return15 }
16
17 if (k == ) {
18 replaceStaleEntry(key,value,i);
19 20 21 }
22
23 tab[i] = new Entry(key,value);
24 int sz = ++size;
25 if (!cleanSomeSlots(i,sz) && sz >= threshold)
26 rehash();
27 }
将ThreadLocalMap定义在Thread类内部看起来更符合逻辑
但是ThreadLocalMap并不需要Thread对象来操作,所以定义在Thread类内只会增加一些不必要的开销。
定义在ThreadLocal类中的原因是ThreadLocal类负责ThreadLocalMap的创建和使用
总的来说就是,ThreadLocalMap不是必需品,定义在Thread中增加了成本,定义在ThreadLocal中按需创建。