setInitialValue在Map不存在的时候调用
private T setInitialValue() { //调用initialValue生成一个初始的value值,深入initialValue函数,我们可知它就是返回一个null T value = initialValue(); Thread t = Thread.currentThread(); //获取ThreadLocalMap ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else //如果不存在则会调用createMap创建ThreadLocalMap createMap(t, value); return value; } void createMap(Thread t, T firstValue) { //new一个ThreadLocalMap对象进去 t.threadLocals = new ThreadLocalMap(this, firstValue); } set方法 public void set(T value) { //获取当前线程 Thread t = Thread.currentThread(); //获取map ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } map.set(this,value)方法 private void set(ThreadLocal<?> key, Object value) { Entry[] tab = table; int len = tab.length; //根据key计算出位置 int i = key.threadLocalHashCode & (len-1); //循环检测 for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) { ThreadLocal<?> k = e.get(); //如果Entry已经存在并且key等于传入的key,那么这时候直接给这个Entry赋新的value值。 if (k == key) { e.value = value; return; } //如果Entry存在,但是key为null,则调用replaceStaleEntry来更换这个key为空的Entry if (k == null) { replaceStaleEntry(key, value, i); return; } } //创建一个entry tab[i] = new Entry(key, value); //sz加1 int sz = ++size; if (!cleanSomeSlots(i, sz) && sz >= threshold) rehash(); } remove方法 public void remove() { //获取map ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null) //调用map的remove m.remove(this); } ThreadLocalMap.remove(this)方法 private void remove(ThreadLocal<?> key) { Entry[] tab = table; int len = tab.length; //获取索引位置 int i = key.threadLocalHashCode & (len-1); //循环遍历table表 for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) { //如果找到,调调用清除相关方法,并结束循环 if (e.get() == key) { //调用weakrefrence的clear()清除引用 e.clear(); //连续段清除 expungeStaleEntry(i); return; } } } 资料Java问题收集