Java ConcurrentHashMap
// 首次初始化table
private final Node<K,V>[] initTable() { Node<K,V>[] tab; int sc; while ((tab = table) == null || tab.length == 0) { // ①
// ② if ((sc = sizeCtl) < 0) Thread.yield(); // lost initialization race; just spin else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { try {
// ③ 别的线程完成了初始化后设置了sizeCtl导致其值不小于0
// 具体而言: while 执行到①时满足,执行到②时别的线程完成了初始化导致sizeCtl 不满足小于0条件, 执行逻辑
// 进入到了 else if流程,内部避免重复初始化 需要增加对table非空的判断。
if ((tab = table) == null || tab.length == 0) { int n = (sc > 0) ? sc : DEFAULT_CAPACITY; @SuppressWarnings("unchecked") Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n]; table = tab = nt; sc = n - (n >>> 2); // ④ n - 0.25n = 0.75n 扩容阈值 } } finally { sizeCtl = sc; // 初始化完成后sizeCtl设置为扩容阈值 } break; } } return tab; }
final V putVal(K key, V value, boolean onlyIfAbsent) { if (key == null || value == null) throw new NullPointerException(); int hash = spread(key.hashCode()); int binCount = 0; for (Node<K,V>[] tab = table;;) { Node<K,V> f; int n, i, fh; if (tab == null || (n = tab.length) == 0) tab = initTable(); else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { // CAS取值, 判断是否为null,若为null 新节点直接加入到当前位置 if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null))) // CAS操作,新增节点 break; // no lock when adding to empty bin } else if ((fh = f.hash) == MOVED) // Fwd 节点的hash 为MOVED ,表示当前节点正在扩容 tab = helpTransfer(tab, f); else { V oldVal = null; synchronized (f) { // 锁头节点,保证线程安全 if (tabAt(tab, i) == f) { // CAS取值,判断对象是否变化。链表 -> 转化为红黑树后头结点可能会变化,所以这里增加判断 if (fh >= 0) { // hash值大于0表示节点为链表节点 binCount = 1; for (Node<K,V> e = f;; ++binCount) { K ek; if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) { oldVal = e.val; if (!onlyIfAbsent) e.val = value; break; } Node<K,V> pred = e; if ((e = e.next) == null) { // 遍历链表未找到节点,采用尾插法,将节点插入到连接尾部 pred.next = new Node<K,V>(hash, key, value, null); break; } } } else if (f instanceof TreeBin) { // hash不满足大于0,表示红黑树 Node<K,V> p; binCount = 2; if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key, value)) != null) { oldVal = p.val; if (!onlyIfAbsent) p.val = value; } } } } if (binCount != 0) { if (binCount >= TREEIFY_THRESHOLD) treeifyBin(tab, i); // 树化操作 if (oldVal != null) return oldVal; break; } } } addCount(1L, binCount); // 维护集合长度,并进行扩容相关操作 return null; }