public T get(){ // 获取当前线程 Thread t = Thread.currentThread(); // 获取当前线程的 ThreadLocalMap ThreadLocalMap map = getMap(t); if (map != null) { // 调用 getEntry 根据 key 查找到 value ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); }
private Entry getEntry(ThreadLocal<?> key){ // 根据hash值确定位置,获取元素 int i = key.threadLocalHashCode & (table.length - 1); Entry e = table[i]; if (e != null && e.get() == key) return e; else // 如果 key 不相同或者值为null,调用 getEntryAfterMiss return getEntryAfterMiss(key, i, e); }
// Rehash until we encounter null Entry e; int i; // 循环,直到 tab[i] == null 退出 for (i = nextIndex(staleSlot, len); (e = tab[i]) != null; i = nextIndex(i, len)) { ThreadLocal<?> k = e.get(); // 如果再次发现 key 为 null 的都删掉 if (k == null) { e.value = null; tab[i] = null; size--; } else { // 处理 rehash 情况 int h = k.threadLocalHashCode & (len - 1); if (h != i) { tab[i] = null;
// Unlike Knuth 6.4 Algorithm R, we must scan until // null because multiple entries could have been stale. while (tab[h] != null) h = nextIndex(h, len); tab[h] = e; } } } return i; }