1.引言
网上已经有很多关于ConcurrentHashMap1.8源码的解析,像putval(),get()等方法的源码也不是很复杂,在这就不再赘述了。但是很多文章的tryPresize()扩容方法讲的晦涩难懂,我今天就讲讲我对tryPresize()方法的理解
2.源码解析
首先,tryPresize()方法是在树化桶的链表时调用的,解析见注解
private final void treeifyBin(Node<K,V>[] tab, int index) {
Node<K,V> b; int n, sc;
if (tab != null) {
//当某个桶个节点数大于,但table[]的长度小于最小的长度时(默认64)
// 进行扩容,调整某个桶中结点数量过多的问题
if ((n = tab.length) < MIN_TREEIFY_CAPACITY)TREEIFY_THRESHOLD
tryPresize(n << 1);
......省略
}
接下来看看tryPresize()方法
private final void tryPresize(int size) {
//size在传入之前就已经翻倍了,最终c是一个大于等于(size * 1.5 + 1)的2的幂次方数
int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
tableSizeFor(size + (size >>> 1) + 1);
int sc;
//此时的sizeCtl是cap * 0.75,扩容阈值
while ((sc = sizeCtl) >= 0) {
Node<K,V>[] tab = table; int n;
if (tab == null || (n = tab.length) == 0) {
n = (sc > c) ? sc : c;
//如果此时tab为空,则进行初始化,将sizeCtl设为-1
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 * 0.75
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
}
}
else if (c <= sc || n >= MAXIMUM_CAPACITY)
break;
//tab == table说明还没开始迁移节点
else if (tab == table) {
int rs = resizeStamp(n);
//开始迁移原tab[] 中的数据,此时将sizeCtl设置为一个很大的负值,(rs << RESIZE_STAMP_SHIFT) + 2)必为一个负值
if (U.compareAndSwapInt(this, SIZECTL