我的学习

04_ConcurrentHashMap源码分析

2020-12-16  本文已影响0人  Mr_Qiang

一、 ConcurrentHashMap是如何保证安全的?

结构和1.8的HashMap一样,采用数组加链表/红黑树。在put的时候,如果key 的hash&n-1 的角标i上没有元素,那么通过cas直接放。如果有元素了,那么synchronized i 这个角标的链表/红黑树。再去存放。扩容的时候,通过cas设置角标i的元素为ForwardingNode,才得到线程安全。

  static final class ForwardingNode<K,V> extends Node<K,V> {
        final Node<K,V>[] nextTable;
        ForwardingNode(Node<K,V>[] tab) {
            super(MOVED, null, null, null);
            this.nextTable = tab;
        }

二、 构造

3. 成员属性

注意,ConcurrentHashmap跟HashMap不同的树化的条件。HashMap只要链表大于8,就转红黑树,而ConcurrentHashmap在安全和效率的前提下,但链表大于8的时候,看数组的长度是否大于64,如果不大于64,只扩容,反之才树化。

三、主要方法

1. putValue(K k,V v)

 /** 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;
            /*1. 如果数组长度为null,初始化数组。初始化的时候,先进去看下sizeCtr<0?小于0,则放弃CPU执行权,说明有线程在初始化数组;
            如果不是<0,特别是第一第一个线程进来为0,则先把SizeCtr改成-1,然后自己去初始化数组。*/
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
                /*3. 如果数组不为null,则把数组长度-1&key的hash,作为角标,如果角标为  null,则cas把这个k和value作为一个新的Node放在数组的这个角标上。*/
            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
            }
            /* 如果该角标的hash=-1,则 帮助其他线程去帮助扩容 */
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
            // 4. 锁住该角标上的元素
            
            
                V oldVal = null;
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                    // 5. 如果是链表,遍历链表看是不是存在相同的key了,如果存在根据onlyIfAbsent看是否需要替换value。如果没有相同的key,则挂在最后。binCount+1
                        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;
                                }
                            }
                        }
                        //6. 如果是树,就挂在树下。
                        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;
                            }
                        }
                    }
                }
                //7. 根据binCount>=8,看是否需要树化。
                if (binCount != 0) {
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }

put方法的步骤:

1.1 初始化数组的方法

    private final Node<K,V>[] initTable() {
        Node<K,V>[] tab; int sc;
        while ((tab = table) == null || tab.length == 0) {
        //1. 如果sizeCtl<0,则代表有其他线程正在初始化。则当前线程放弃cpu执行权。
            if ((sc = sizeCtl) < 0)
                Thread.yield(); // lost initialization race; just spin
            // 2. 如果数组长度>=0,则把数组长度设置为-1.(第一次进来肯定>=0)
            
            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                try {
                    if ((tab = table) == null || tab.length == 0) {
                    /* 按长度初始化数组,默认为16 sc=16-4= 12*/
                        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改成了-1,让其他线程来了后放弃Cpu执行权。然后第一个线程继续去初始化数组。

1.2 扩容或树化的方法

当桶的深度>=8的时候,考虑树化,但是不一定真的树化,还会去判断数组的长度是不是>64,如果不是>64,则进行扩容,而不是树化。
注意这个HashMap的不同,HashMap是只要长度>3/4,则扩容。ConcurrentHashMap是链表长度>8,tableSize<64,进行扩容。

    /**
     * Replaces all linked nodes in bin at given index unless table is
     * too small, in which case resizes instead.
     */
    private final void treeifyBin(Node<K,V>[] tab, int index) {
        Node<K,V> b; int n, sc;
        if (tab != null) {
        // 如果数组的长度<64,扩容
            if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
                tryPresize(n << 1);
                //如果长度>64,且桶的深度>8,进行树化。
            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
                synchronized (b) {
                    if (tabAt(tab, index) == b) {
                        TreeNode<K,V> hd = null, tl = null;
                        for (Node<K,V> e = b; e != null; e = e.next) {
                            TreeNode<K,V> p =
                                new TreeNode<K,V>(e.hash, e.key, e.val,
                                                  null, null);
                            if ((p.prev = tl) == null)
                                hd = p;
                            else
                                tl.next = p;
                            tl = p;
                        }
                        setTabAt(tab, index, new TreeBin<K,V>(hd));
                    }
                }
            }
        }
    }

1.3 扩容的方法

 /**
     * Tries to presize table to accommodate the given number of elements.
     *
     * @param size number of elements (doesn't need to be perfectly accurate)
     */
    private final void tryPresize(int size) {
    // 如果数组长度>=2^30/2,则c=2^30;反之为c=size+size/2+1;
        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
            tableSizeFor(size + (size >>> 1) + 1);
        int sc;
        while ((sc = sizeCtl) >= 0) {
            Node<K,V>[] tab = table; int n;
            //如果数组为空,cas sizeCtl为-1,然后去创建指定c长度的Node数组。
            if (tab == null || (n = tab.length) == 0) {
                n = (sc > c) ? sc : c;
                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;
                            //sizeCtl=数组长度的3/4
                            sc = n - (n >>> 2);
                        }
                    } finally {
                        sizeCtl = sc;
                    }
                }
            }
            //如果数组长度>最大容量
            else if (c <= sc || n >= MAXIMUM_CAPACITY)
                break;
                //扩容和搬迁元素
            else if (tab == table) {
                int rs = resizeStamp(n);
                if (sc < 0) {
                    Node<K,V>[] nt;
                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
                        transferIndex <= 0)
                        break;
                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
                        transfer(tab, nt);
                }
                else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                             (rs << RESIZE_STAMP_SHIFT) + 2))
                    transfer(tab, null);
            }
        }
    }

扩容的步骤

1.4 搬迁元素


    /**
     * Moves and/or copies the nodes in each bin to new table. See
     * above for explanation.
     */
    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
        int n = tab.length, stride;
        
        //①. 计算步长 如果stride<16,stride=16;
        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
            stride = MIN_TRANSFER_STRIDE; // subdivide range
            // ②.  初始化新的数组,长度为之前的2倍。nextTable为创建后的数组,transferIndex为之前数组的长度。sizeCtl=int 最大值。
        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;
        }
        //创建一个有MOVED的新的长度的Node数组。
        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
                }
            }
            //④. 如果之前的角标i元素为null,则把之前角标为i的位置设置成MOVED的Node数组,证明此角标已经搬迁了。
            else if ((f = tabAt(tab, i)) == null)
                advance = casTabAt(tab, i, null, fwd);
                //⑤. 如果角标为i的已经是MOVED,说明已经有其他线程正在扩容,需要帮助一起搬运元素到新的数组。当前线程可以从i--开始搬运其他的角标元素。
            else if ((fh = f.hash) == MOVED)
                advance = true; // already processed
            else {
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        Node<K,V> ln, hn;
                        //⑥. 如果角标i的元素f的hash>=0,则说明是链表
                        if (fh >= 0) {
                            int runBit = fh & n;
                            Node<K,V> lastRun = f;
                            //这里比较复杂!是为了找出一个点,这个点后面的元素都是 hash & n相同的。这样在迁移的时候,只用迁移这个点之前的元素和这个点就行了。因为这个点后挂着的hash&n都相同,迁移后都在一个位置上,链表只需要迁移这个节点就行。看下图。
                            for (Node<K,V> p = f.next; p != null; p = p.next) {
                                int b = p.hash & n;
                                if (b != runBit) {
                                    runBit = b;
                                    lastRun = p;
                                }
                            }
                            // 此处和下面的for循环都是把所有节点根据ph&n==0分成两组,一组是ln链表,一组是hn链表。
                            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);
                            }
                            //然后把ln放在新数组原来角标的位置,hn让在新数组i+n的位置。设置f为fwd(MOVED),继续i--;
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            setTabAt(tab, i, fwd);
                            advance = true;
                        }
                        //⑦. 如果角标i元素f为树类型,则搬迁这个树。
                        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;
                        }
                    }
                }
            }
        }
    }

搬迁元素的步骤

其中链表的搬迁过程

                        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;
                        }

这段代码的整体步骤:

其中红黑树的的搬迁过程

2. V get(Object key)

很简单,跟HashMap一样,没加锁。

    public V get(Object key) {
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        int h = spread(key.hashCode());
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (e = tabAt(tab, (n - 1) & h)) != null) {
            if ((eh = e.hash) == h) {
                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                    return e.val;
            }
            else if (eh < 0)
                return (p = e.find(h, key)) != null ? p.val : null;
            while ((e = e.next) != null) {
                if (e.hash == h &&
                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
                    return e.val;
            }
        }
        return null;
    }
上一篇下一篇

猜你喜欢

热点阅读