Loading

ConcurrentHashMap的put方法

使用JDK8

源码:

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

    /** Implementation for put and putIfAbsent */
    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) {
                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)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        if (fh >= 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) {
                            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;
    }

分析:

put

put方法进入,然后进入putVal方法,可以看到onlyIfAbsent的值为false。

那么我们putputIfAbsent对比:

    public V putIfAbsent(K key, V value) {
        return putVal(key, value, true);
    }

onlyIfAbsent为true,当该位置为没有值,则加入。如果该位置有值,则保持原来的值,不进行覆盖。

如果大家还是不清楚那就看看网上关于putIfAbsent方法的使用讲解。

putVal

  • spread方法计算hash

  • 进入table数组(ConcurrentHashMap结构是Node数组+链表+红黑树)

  • 如果table数组为null,则先initTable方法来初始化数组

        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 {
                        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);
                        }
                    } finally {
                        sizeCtl = sc;
                    }
                    break;
                }
            }
            return tab;
        }
    

    sizeCtl小于零说明有其他线程也在初始化数组,则让当前线程yield,让出cpu时间片。那如果我们自己初始化数组,则需要CAS加自旋。

  • 如果该数组位置上没有元素,那么则直接添加

  • 如果f.hash等于-1,说明需要扩容了

  • 最后我们对链表头结点,或者对红黑树头结点加锁

  • 如果是链表,遍历之,如果遇到key的值(注意不是key的hash值)和链表中的key的值有相等的,则覆盖value。如果遍历到最后都没遇到key值一样的,那就放到链表结尾吧。

  • 如果是树,那就用putTreeVal方法了

posted @ 2021-05-25 19:26  KeBoom  阅读(183)  评论(0编辑  收藏  举报