知识:
// ConcurrentHashMap.classprivate void rehash(HashEntry<K,V> node) {HashEntry<K,V>[] oldTable = table;// 旧的长度int oldCapacity = oldTable.length;// 扩容一倍int newCapacity = oldCapacity << 1;threshold = (int)(newCapacity * loadFactor);// 创建新的tableHashEntry<K,V>[] newTable =(HashEntry<K,V>[]) new HashEntry[newCapacity];int sizeMask = newCapacity - 1;for (int i = 0; i < oldCapacity ; i++) {HashEntry<K,V> e = oldTable[i];if (e != null) {HashEntry<K,V> next = e.next;int idx = e.hash & sizeMask;if (next == null) // Single node on listnewTable[idx] = e;else { // Reuse consecutive sequence at same slotHashEntry<K,V> lastRun = e;int lastIdx = idx;// <1> 不知道为什么,获取 lastNode 然后,计算lastNode在newTable未知,然后设置进去for (HashEntry<K,V> last = next;last != null;last = last.next) {int k = last.hash & sizeMask;if (k != lastIdx) {lastIdx = k;lastRun = last;}}newTable[lastIdx] = lastRun;// <2> 这个for是头插法,会将 node 的每个节点重新计算 index 下表,然后再设置到 newTable// Clone remaining nodesfor (HashEntry<K,V> p = e; p != lastRun; p = p.next) {V v = p.value;int h = p.hash;int k = h & sizeMask;HashEntry<K,V> n = newTable[k];newTable[k] = new HashEntry<K,V>(h, p.key, v, n);}}}}int nodeIndex = node.hash & sizeMask; // add the new nodenode.setNext(newTable[nodeIndex]);newTable[nodeIndex] = node;table = newTable;}
// ConcurrentHashMap.classprivate HashEntry<K,V> scanAndLockForPut(K key, int hash, V value) {HashEntry<K,V> first = entryForHash(this, hash);HashEntry<K,V> e = first;HashEntry<K,V> node = null;int retries = -1; // negative while locating node// <1> 尝试加锁while (!tryLock()) {HashEntry<K,V> f; // to recheck first below// <2> 获取 node 最后一个元素if (retries < 0) {if (e == null) {if (node == null) // speculatively create nodenode = new HashEntry<K,V>(hash, key, value, null);retries = 0;}else if (key.equals(e.key))retries = 0;elsee = e.next;}// <3> 最大 tryLock 次数else if (++retries > MAX_SCAN_RETRIES) {lock();break;}// <4> node 变更,再次检查else if ((retries & 1) == 0 &&(f = entryForHash(this, hash)) != first) {e = first = f; // re-traverse if entry changedretries = -1;}}return node;}