ConcurrentHashMap源码

JDK8源码

put操作

    public V put(K key, V value) {
        return putVal(key, value, false);	//调用putVal
    }

putVal:

    final V putVal(K key, V value, boolean onlyIfAbsent) {
	//key和value都不能为null
        if (key == null || value == null) throw new NullPointerException();
        int hash = spread(key.hashCode());
        int binCount = 0;	//表示链表长度
        for (Node<K,V>[] tab = table;;) {
	//f:链表头节点 fh:头节点的hash  i:链表在table中的下标  n:table长度
            Node<K,V> f; int n, i, fh;
            if (tab == null || (n = tab.length) == 0)	//判断table是否创建
                tab = initTable();	//初始化table,使用CAS操作,无需加锁。创建后进入下一轮循环
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {	//判断头节点是否为空
			//如果头节点为空,则创建头节点,添加的元素为头节点。创建使用cas操作
                if (casTabAt(tab, i, null,
                             new Node<K,V>(hash, key, value, null)))
                    break;                   // no lock when adding to empty bin
            }
            else if ((fh = f.hash) == MOVED)	//hash为负数MOVED,表示有其他线程正在扩容
			//当前put不是阻塞等待,而是会去帮助扩容
                tab = helpTransfer(tab, f);
            else {	//出现hash冲突,链地址法put操作
                V oldVal = null;
                synchronized (f) {	//只锁住当前的链表头节点
                    if (tabAt(tab, i) == f) {	//再次确认头节点没有改变
                        if (fh >= 0) {	//>=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)))) {	//如果存在相同的key,则覆盖旧值
                                    oldVal = e.val;
                                    if (!onlyIfAbsent)
                                        e.val = value;
                                    break;
                                }
                                Node<K,V> pred = e;
                                if ((e = e.next) == null) {	//不存在相同的key,则追加节点
                                    pred.next = new Node<K,V>(hash, key,
                                                              value, null);
                                    break;
                                }
                            }
                        }
                        else if (f instanceof TreeBin) {	//节点是红黑树
                            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);	//元素个数加1
        return null;
    }

initTable(初始化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)) {	//试图将sizeCtl改为-1,表示正在创建table
                try {
                    if ((tab = table) == null || tab.length == 0) {
                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;	//获取要创建的table的容量大小
                        @SuppressWarnings("unchecked")
                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                        table = tab = nt;
                        sc = n - (n >>> 2);	//计算下次需要扩容的阈值
                    }
                } finally {
                    sizeCtl = sc;
                }
                break;
            }
        }
        return tab;
    }

addCount(table中元素个数增加,并检查是否需要扩容,如果需要则进行扩容)

    private final void addCount(long x, int check) {
        CounterCell[] as; long b, s;
        if ((as = counterCells) != null ||	//如果累加数组as不为空,表示有其他线程也在累加
		//没有其他线程累加,则在baseCount上累加。如果baseCount累加失败,则进入
            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
            CounterCell a; long v; int m;
            boolean uncontended = true;
            if (as == null || (m = as.length - 1) < 0 ||	//累加数组还未创建
                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||	//没有累加单元
                !(uncontended =
                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {	//有累加数组和累加单元,则执行cas累加
				  //如果上述都失败,创建累加数组和累加单元,循环尝试累加
                fullAddCount(x, uncontended);
                return;
            }
            if (check <= 1)	//检查链表长度,如果大于1,可能需要扩容
                return;
            s = sumCount();	//获取元素个数
        }
        if (check >= 0) {
            Node<K,V>[] tab, nt; int n, sc;
            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&	//元素个数超过阈值,需要进行扩容
                   (n = tab.length) < MAXIMUM_CAPACITY) {
                int rs = resizeStamp(n) << RESIZE_STAMP_SHIFT;
                if (sc < 0) {	//sc为负数,有线程正在扩容
                    if (sc == rs + MAX_RESIZERS || sc == rs + 1 ||
                        (nt = nextTable) == null || transferIndex <= 0)	//新table还未创建
                        break;
                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))	//新table已经创建,则帮忙扩容
                        transfer(tab, nt);
                }
                else if (U.compareAndSwapInt(this, SIZECTL, sc, rs + 2))	//cas操作,sc改为负数
                    transfer(tab, null);	//创建新table,进行扩容
                s = sumCount();
            }
        }
    }

transfer(扩容操作,将每个节点复制到新的table数组中)

    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {	//tab:原始table,nextTab:扩容后的新的table
        int n = tab.length, stride;
        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
            stride = MIN_TRANSFER_STRIDE; // subdivide range
			//新的table还未创建,则创建新table,大小为原table<<1
        if (nextTab == null) {            // initiating
            try {
                @SuppressWarnings("unchecked")
                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
                nextTab = nt;
            } catch (Throwable ex) {      // try to cope with OOME
                sizeCtl = Integer.MAX_VALUE;
                return;
            }
            nextTable = nextTab;
            transferIndex = n;
        }
        int nextn = nextTab.length;
        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
        boolean advance = true;
        boolean finishing = false; // to ensure sweep before committing nextTab
        for (int i = 0, bound = 0;;) {
            Node<K,V> f; int fh;
            while (advance) {
                int nextIndex, nextBound;
                if (--i >= bound || finishing)
                    advance = false;
                else if ((nextIndex = transferIndex) <= 0) {
                    i = -1;
                    advance = false;
                }
                else if (U.compareAndSwapInt
                         (this, TRANSFERINDEX, nextIndex,
                          nextBound = (nextIndex > stride ?
                                       nextIndex - stride : 0))) {
                    bound = nextBound;
                    i = nextIndex - 1;
                    advance = false;
                }
            }
            if (i < 0 || i >= n || i + n >= nextn) {
                int sc;
                if (finishing) {
                    nextTable = null;
                    table = nextTab;
                    sizeCtl = (n << 1) - (n >>> 1);
                    return;
                }
                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
                    if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
                        return;
                    finishing = advance = true;
                    i = n; // recheck before commit
                }
            }
            else if ((f = tabAt(tab, i)) == null)	//如果链表的头节点为null,说明该链表已经移动完毕,将链表头替换为fwd节点(hash为MOVED=-1),表示已经移动
                advance = casTabAt(tab, i, null, fwd);
            else if ((fh = f.hash) == MOVED)	//此链表已经移动完毕,循环处理下一个链表
                advance = true; // already processed
            else {	//链表中有元素
                synchronized (f) {	//加锁移动元素
                    if (tabAt(tab, i) == f) {
                        Node<K,V> ln, hn;
                        if (fh >= 0) {	//普通链表节点
                            int runBit = fh & n;
                            Node<K,V> lastRun = f;
                            for (Node<K,V> p = f.next; p != null; p = p.next) {
                                int b = p.hash & n;
                                if (b != runBit) {
                                    runBit = b;
                                    lastRun = p;
                                }
                            }
                            if (runBit == 0) {
                                ln = lastRun;
                                hn = null;
                            }
                            else {
                                hn = lastRun;
                                ln = null;
                            }
                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
                                int ph = p.hash; K pk = p.key; V pv = p.val;
                                if ((ph & n) == 0)
                                    ln = new Node<K,V>(ph, pk, pv, ln);
                                else
                                    hn = new Node<K,V>(ph, pk, pv, hn);
                            }
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            setTabAt(tab, i, fwd);
                            advance = true;
                        }
                        else if (f instanceof TreeBin) {	//红黑树节点
                            TreeBin<K,V> t = (TreeBin<K,V>)f;
                            TreeNode<K,V> lo = null, loTail = null;
                            TreeNode<K,V> hi = null, hiTail = null;
                            int lc = 0, hc = 0;
                            for (Node<K,V> e = t.first; e != null; e = e.next) {
                                int h = e.hash;
                                TreeNode<K,V> p = new TreeNode<K,V>
                                    (h, e.key, e.val, null, null);
                                if ((h & n) == 0) {
                                    if ((p.prev = loTail) == null)
                                        lo = p;
                                    else
                                        loTail.next = p;
                                    loTail = p;
                                    ++lc;
                                }
                                else {
                                    if ((p.prev = hiTail) == null)
                                        hi = p;
                                    else
                                        hiTail.next = p;
                                    hiTail = p;
                                    ++hc;
                                }
                            }
                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            setTabAt(tab, i, fwd);
                            advance = true;
                        }
                    }
                }
            }
        }
    }
posted @ 2024-01-29 21:33  ︶ㄣ演戲ㄣ  阅读(11)  评论(0)    收藏  举报