深入理解ConcurrentHashMap(JDK8)

前言

前面我们讲了HashMap的源码,知道HashMap是线程不安全的。今天我们就来讲一讲在JUC( java.util.concurrent)并发包中线程安全的HashMap-----ConcurrentHashMap
想了解HashMap源码的同学可以去看之前的文章链接: 深入理解HashMap(JDK8)

ConcurrentHashMap源码

注意:我会把源码中每个方法的作用都注释出来,可以参考注释进行理解。

put()

    final V putVal(K key, V value, boolean onlyIfAbsent) {
    
    
    	//concurrentHashMap不允许空值
        if (key == null || value == null) throw new NullPointerException();
        //获取key的hash值
        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插入,保证线程安全
                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 {
    
    
            	//当前位置存在hash冲突
                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;
    }

第一步,就是去判断kye,value的值,因为ConcurrentHashMap不允许有null值
第二步,当数组为空的时候,initTable初始化数组

initTable()初始化数组

private final Node<K,V>[] initTable() {
    
    
        Node<K,V>[] tab; int sc;
        while ((tab = table) == null || tab.length == 0) {
    
    
        	//sizeCtl《0 表示初始化的工作已经被其他线程抢去了
            if ((sc = sizeCtl) < 0)
                Thread.yield(); // lost initialization race; just spin
                //否则,通过cas操作将SIZECTL变为-1,表示抢占了
            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);//12
                    }
                } finally {
    
    
                	//最后将阈值赋值
                    sizeCtl = sc;
                }
                break;
            }
        }
        return tab;
    }
private transient volatile int sizeCtl;//用于判断是否被其他线程抢占,类似于锁

考虑到线程安全为题,这里利用volatile 修饰的sizeCtl:

  1. 如果sizeCtl<0,表示初始化工作已经被其他线程抢走
  2. 否则,就通过CAS操作,将sizeCtl变为-1,表示抢占到了锁,在初始化数组,最后将阈值赋值给sizeCtl

初始化工作完成后,就该插入 值了:

  • 第一步:如果当前下表位置的值为空,通过CAS操作,将值直接插入到数组中
  • 第二步:当前位置有值,存在hash冲突。通过synchronized对当前节点加锁,保证线程安全
  • 第三步:判断当前节点hash值:如果大于等于0,这代表是链表结构;否则如果该节点类型是红黑树类型,则进行红黑树操作
  • 第四步:添加完数据后,再去判断链表的长度binCount,如果大于8,则转换成红黑树

值插入完毕,就需要通过addCount方法去更新数组的大小了

addCount()更新数组长度

//volatile 修饰,保证可见性
private transient volatile CounterCell[] counterCells;

   @sun.misc.Contended static final class CounterCell {
    
    
        volatile long value;
        CounterCell(long x) {
    
     value = x; }
    }

    final long sumCount() {
    
    
        CounterCell[] as = counterCells; CounterCell a;
        long sum = baseCount;
        if (as != null) {
    
    
            for (int i = 0; i < as.length; ++i) {
    
    
                if ((a = as[i]) != null)
                    sum += a.value;
            }
        }
        return sum;
    }


private final void addCount(long x, int check) {
    
    
		//为了防止多线程同时去增加长度时,一直自旋导致性能man
		//所以多线程时,一个线程一个CounterCell对象
        CounterCell[] as; long b, s;
        //第一部分
        
        //如果counterCells不为空
        //或者CAS更新BASECOUNT失败
        if ((as = counterCells) != null ||
            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
    
    
            //表示有很多线程在抢占更新BASECOUNT值
            CounterCell a; long v; int m;
            //冲突标志,默认是没有冲突
            boolean uncontended = true;
            //如果CounterCell数组为空
            //通过当前线程&CounterCells数组的长度获得下标,且当前下标上没值
            //如果CAS更新当前counterCell对象中value的值失败
            if (as == null || (m = as.length - 1) < 0 ||
                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
                !(uncontended =
                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
    
    
                //进入
                fullAddCount(x, uncontended);
                return;
            }
            //链表的长度小于1,不需要扩容
            if (check <= 1)
                return;
             //用BASECOUNT加上所有线程增加的长度,即CounterCell数组中的value值相加+BASECOUNT
            s = sumCount();
        }
//第二部分
        //如果的binCount大于0,需要去检查是否需要扩容
        if (check >= 0) {
    
    
            Node<K,V>[] tab, nt; int n, sc;
            //如果当前数组长度大于阈值sizeCtl,
            //且node数组不为空,
            //且node数组的长度小于默认数组的最大值
            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
                   (n = tab.length) < MAXIMUM_CAPACITY) {
    
    
                   //生成一个唯一的扩容戳,高位表示唯一的扩容标记,低位表示参与扩容的线程数
                int rs = resizeStamp(n);
                //如果sizeCtl<0,表示有线程在进行扩容了
                if (sc < 0) {
    
    
                //1. sc >>> RESIZE_STAMP_SHIFT!=rs,判断高位的扩容标记不相同,则不能参与扩容
	            //2. sc == rs + 1,表示扩容已经结束
	            //3.  sc == rs + MAX_RESIZERS ,表示当前帮助扩容的线程数已经达到最大值
	            //4. (nt = nextTable) == null,表示扩容已经结束
	            //5.  transferIndex <= 0,表示所有的 transfer 任务都被领取完了
                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
                        transferIndex <= 0)
                        break;
                     //cas操作将SIZECTL+1
                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
                    //去协助扩容
                        transfer(tab, nt);
                }
                //没有线程在扩容,
                //自己开始扩容,将SIZECTL+2
                else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                             (rs << RESIZE_STAMP_SHIFT) + 2))
                    transfer(tab, null);
                s = sumCount();
            }
        }
    }

这里为了防止多线程同时去增加长度时,一直自旋导致性能变差,所以采用CounterCell数组去管理多个线程所要去增加的长度
addCount方法分为两部分:

  • 第一部分:通过CounterCell数组去更新当前线程需要增加的长度
  • 第二部分:判断Node数组是否需要扩容

先来看第一部分的代码:
如果counterCells不为空,或者CAS更新BASECOUNT失败,表示当前线程竞争激烈,需要通过CounterCell数组去管理

fullAddCount()

private final void fullAddCount(long x, boolean wasUncontended) {
    
    
        int h;
        //生成一个当前线程的随机数
        if ((h = ThreadLocalRandom.getProbe()) == 0) {
    
    
            ThreadLocalRandom.localInit();      // force initialization
            h = ThreadLocalRandom.getProbe();
            wasUncontended = true;
        }
        boolean collide = false;                // True if last slot nonempty
        for (;;) {
    
    
            CounterCell[] as; CounterCell a; int n; long v;
            //如果数组不为空
            if ((as = counterCells) != null && (n = as.length) > 0) {
    
    
            	//当前下标位置等于null
                if ((a = as[(n - 1) & h]) == null) {
    
    
                	//如果cellsBusy =0,表示没线程占用
                    if (cellsBusy == 0) {
    
                // Try to attach new Cell
                    	//初始化CounterCell对象
                        CounterCell r = new CounterCell(x); // Optimistic create
                        //去抢占锁
                        //CAS操作改变CELLSBUSY的值
                        if (cellsBusy == 0 &&
                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
    
    
                            //抢到锁,将值插入
                            boolean created = false;
                            try {
    
                   // Recheck under lock
                                CounterCell[] rs; int m, j;
                                if ((rs = counterCells) != null &&
                                    (m = rs.length) > 0 &&
                                    rs[j = (m - 1) & h] == null) {
    
    
                                    rs[j] = r;
                                    created = true;
                                }
                            } finally {
    
    
                            //最后,放开所
                                cellsBusy = 0;
                            }
                            if (created)
                                break;
                            continue;           // Slot is now non-empty
                        }
                    }
                    collide = false;
                }
                //如果之前在外面CAS将当前CounterCell 的值改变失败
                else if (!wasUncontended)       // CAS already known to fail
                	//重新CAS
                    wasUncontended = true;      // Continue after rehash
                 //成功CAS,返回
                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
                    break;
                else if (counterCells != as || n >= NCPU)
                    collide = false;            // At max size or stale
                else if (!collide)
                    collide = true;
                 //cellsBusy ==0
                 //且CAS 值CELLSBUSY成功
                else if (cellsBusy == 0 &&
                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
    
    
                    try {
    
    
                    	//抢到锁了
                    	//当前线程太多,竞争激烈,需要扩容CounterCell数组
                        if (counterCells == as) {
    
    // Expand table unless stale
                            CounterCell[] rs = new CounterCell[n << 1];
                            for (int i = 0; i < n; ++i)
                                rs[i] = as[i];
                            counterCells = rs;
                        }
                    } finally {
    
    
                        cellsBusy = 0;
                    }
                    collide = false;
                    continue;                   // Retry with expanded table
                }
                h = ThreadLocalRandom.advanceProbe(h);
            }
            //counterCells数组为空
            else if (cellsBusy == 0 && counterCells == as &&
                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
    
    
                boolean init = false;
                try {
    
                               // Initialize table
                    if (counterCells == as) {
    
    
                    	//初始化一个新的CounterCell数组,默认长度2
                        CounterCell[] rs = new CounterCell[2];
                        rs[h & 1] = new CounterCell(x);
                        counterCells = rs;
                        init = true;
                    }
                } finally {
    
    
                    cellsBusy = 0;
                }
                if (init)
                    break;
            }
            //最后再去尝试一次修改BASECOUNT的值
            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
                break;                          // Fall back on using base
        }
    }

这里对CounterCell 数组处理的逻辑主要分为:

  1. 如果CounterCell数组不为空,且当前下表位置为空,通过cellsBusy 标志去抢占锁,通过CAS操作将值插入到数组中,最后释放锁
    1. 如果CAS赋值失败,表示竞争激烈,需要对CounterCell数组进行扩容,长度是原来的两倍
  2. 数组为空,且cellsBusy标记为0,表示没有线程去处理,初始化一个长度为2的CounterCell数组
  3. 最后通过CAS再去尝试一下修改BASECOUNT数组的长度

再来看第二部分:如果binCount大于0,就需要检查Node数组是否需要扩容
当Node数组长度大于阈值sizeCtl,且node数组不为空,且node数组的长度小于默认数组的最大值,表示可以扩容了:

  1. 如果sizeCtl<0,表示当前有线程在扩容了,紧接着去判断当前线程是否还需要去扩容:
    1. sc >>> RESIZE_STAMP_SHIFT!=rs,判断高位的扩容标记不相同,则不能参与扩容
    2. sc == rs + 1,表示扩容已经结束
    3. sc == rs + MAX_RESIZERS ,表示当前帮助扩容的线程数已经达到最大值
    4. (nt = nextTable) == null,表示扩容已经结束
    5. transferIndex <= 0,表示所有的 transfer 任务都被领取完了
  2. 如果能帮助扩容,通过CAS将sizeCtl+1,调用transfer方法,进行扩容
  3. 如果sizeCtl>0,自己开始扩容,将SIZECTL+2

接下来,我们看看扩容方法

transfer()扩容

    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
    
    
        int n = tab.length, stride;
        //通过cpu数去分配数组,保证每个cpu处理的数据一样多
        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
            stride = MIN_TRANSFER_STRIDE; // subdivide range
            
            //nextTab 未初始化,nextTab 是用来扩容的 node 数组
        if (nextTab == null) {
    
                // initiating
            try {
    
    
                @SuppressWarnings("unchecked")
                //新建一个扩容后的数组
                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
                //赋值给nextTab 
                nextTab = nt;
            } catch (Throwable ex) {
    
          // try to cope with OOME
            	//出现异常 sizeCtl 默认给Integer最大值
                sizeCtl = Integer.MAX_VALUE;
                return;
            }
            nextTable = nextTab;
            //更新转移下标,表示转移时的下标,比如16
            transferIndex = n;
        }
        //新数组的长度 32
        int nextn = nextTab.length;
        // 创建一个 fwd 节点,表示一个正在被迁移的 Node,并且它的 hash 值为-1(MOVED),也
		//就是前面我们在讲 putval 方法的时候,会有一个判断 MOVED 的逻辑。它的作用是用来占位,表示
		//原数组中位置 i 处的节点完成迁移以后,就会在 i 位置设置一个 fwd 来告诉其他线程这个位置已经
		//处理过了
        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;
                //bound 标识边界,--i标识下一个处理的节点
                if (--i >= bound || finishing)
                	//处理完毕
                    advance = false;
                 //任务已经分配完毕
                else if ((nextIndex = transferIndex) <= 0) {
    
    
                    i = -1;
                    advance = false;
                }
                //cas操作TRANSFERINDEX,为当前线程分配任务,
                //处理的节点区间(nextBound,nextIndex)->(0,15)
                else if (U.compareAndSwapInt
                         (this, TRANSFERINDEX, nextIndex,
                          nextBound = (nextIndex > stride ?
                                       nextIndex - stride : 0))) {
    
    
                    bound = nextBound;//0
                    i = nextIndex - 1;//15
                    advance = false;
                }
            }
            
            //分配任务完成
            if (i < 0 || i >= n || i + n >= nextn) {
    
    
                int sc;
                //扩容完成
                if (finishing) {
    
    
                	//删除成员变量nextTable ,方便fc
                    nextTable = null;
                    //更新全局变量
                    table = nextTab;
                    //更新阈值
                    sizeCtl = (n << 1) - (n >>> 1);
                    return;
                }
                //CAS 操作对 sizeCtl 的低 16 位进行减 1,代表做完了属于自己的任务
                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 处是空的,没有任何节点,那么放入刚刚初始化的 ForwardingNode ”空节点“
            else if ((f = tabAt(tab, i)) == null)
                advance = casTabAt(tab, i, null, fwd);
                //表示该位置已经完成了迁移,也就是如果线程 A 已经处理过这个节点,
                //那么线程 B 处理这个节点时,hash 值一定为 MOVED
            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;
                        }
                    }
                }
            }
        }
    }

transfer 方法主要分为两部分:

  • 第一部分:将数组扩容,并根据CPU数,均匀地分配所有的节点,保证每条线程的处理量一样。即:第一个发起数据迁移的线程会将 transferIndex 指向原数组最后的位置,然后从后往前的 stride 个任务属于第一个线程,然后将 transferIndex 指向新的位置,再往前的 stride 个任务属于第二个线程,依此类推
  • 第二部分:数据迁移
  1. 处理链表:和HashMap一样,通过fh & n将链表分为两组,一组的下标和之前的下标一样;另一组的小标是之前的下标+之前数组的长度,最后统一移到两个不同的下标处
  2. 处理红黑树的迁移
  3. 最后,扩容完毕

与JDK7的区别

锁的使用

JDK7采用分段Segment分段锁,而jdk8采用CAS+Synchronize保证并发安全

数据结构

dk7使用的是数组+链表来实现,而jdk8使用数组+链表+红黑树实现。采用红黑树是为了防止链越来越长导致查询效率越来越低的问题。链表查询时间复杂度:O(n),红黑树查询时间复杂度:O(logN)

总结

  • ConcurrentHashMap采用CAS+Synchronize保证并发安全
  • ConcurrentHashMap不允许key或value值为空
  • 和HashMap一样,ConcurrentHashMap使用数组+单项链表+红黑树实现

猜你喜欢

转载自blog.csdn.net/xzw12138/article/details/106546756
今日推荐