tryPresize里面部分代码和addCount的部分代码类似,看起来会稍微简单一些
private final void tryPresize(int size) {
//对size进行修复,主要目的是防止传入的值不是一个2次幂的整数,然后通过tableSizeFor来讲入参转化为离该整数最近的2次幂
int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
tableSizeFor(size + (size >>> 1) + 1);
int sc;
while ((sc = sizeCtl) >= 0) {
Node<K,V>[] tab = table; int n;
//下面这段代码和initTable是一样的,如果table没有初始化,则开始初始化
if (tab == null || (n = tab.length) == 0) {
n = (sc > c) ? sc : c;
if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
if (table == tab) {
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = nt;
sc = n - (n >>> 2);//0.75
}
} finally {
sizeCtl = sc;
}
}
}
//
else if (c <= sc || n >= MAXIMUM_CAPACITY)
break;
else if (tab == table) {//这段代码和addCount后部分代码是一样的,做辅助扩容操作
int rs = resizeStamp(n);
if (sc < 0) {
Node<K,V>[] nt;
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || sc == rs + MAX_RESIZERS || (nt = nextTable) == null || transferIndex <= 0)
break;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
transfer(tab, nt);
}
else if (U.compareAndSwapInt(this, SIZECTL, sc, (rs << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
}
}
}