// Rehash until we encounter null Entry e; int i; // 往后遍历 for (i = nextIndex(staleSlot, len); (e = tab[i]) != null; i = nextIndex(i, len)) { ThreadLocal<?> k = e.get(); // 直接清理 if (k == null) { e.value = null; tab[i] = null; size--; } else { // 进行rehash重新存放位置 inth= 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; }
cleanSomeSlots()
每次循环n/=2,n是table[]数组的长度,直到n==0停止清理,也是线性清理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
privatebooleancleanSomeSlots(int i, int n) { booleanremoved=false; Entry[] tab = table; intlen= tab.length; do { i = nextIndex(i, len); Entrye= tab[i]; if (e != null && e.get() == null) { n = len; removed = true; i = expungeStaleEntry(i); } } while ( (n >>>= 1) != 0); return removed; }
扩容
1 2 3 4 5 6 7 8 9 10 11 12 13
// threshold 默认 2/3 * len if (!cleanSomeSlots(i, sz) && sz >= threshold) rehash();