ConcurrentHashMap1.8解析

ConcurrentHashMap的结构和HashMap基本相同,由 数组+链表+红黑树 组成,只是在并发上面做了很多处理.

先了解下重要的变量和内部类

static final int MOVED     = -1; // hash for forwarding nodes
//数组,这里的Node有三类,链表头节点、树的根节点、ForwardingNode节点
transient volatile Node<K,V>[] table; 
//扩容时创建的数组,设计为成员变量的原因是因为扩容会有多个线程协助完成,必须对每个线程可见
private transient volatile Node<K,V>[] nextTable;
//多个作用 -1表示正在初始化
//正数表示下一次扩容的阙值
//-N的时候 高16位是由数组长度(n)计算出来的标示位,正在运行的线程可以通过这个标示位判断扩容是否结束
//低16位表示正在扩容的线程数(N-1),因为-1表示初始化,所以计数从-2开始
private transient volatile int sizeCtl;
//一个特殊的节点,hash值为MOVED,当扩容的线程把原数组的某个位置的节点全部转移后,
//会在这个位置放上ForwardingNode节点,表示该位置已经扩容了,防止put操作插入了错误的位置
//值得一提的是就算正在扩容,put操作发现插入的位置不是ForwardingNode节点,照样可以正常操作
//这表示ConcurrentHashMap可以实现扩容和put的并发操作
static final class ForwardingNode<K,V> extends Node<K,V>

put操作源码

	public V put(K key, V value) {
        return putVal(key, value, false);
    }
    
    final V putVal(K key, V value, boolean onlyIfAbsent) {
        //和hashMap不同的是,concurrentHashMap的key和value都不允许为null
        //concurrenthashmap它们是用于多线程的,并发的 ,如果map.get(key)得到了null,
        // 不能判断到底是映射的value是null,还是因为没有找到对应的key而为空,
        // 而用于单线程状态的hashmap却可以用containKey(key) 去判断到底是否包含了这个null。
        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;
            //如果是第一次put,进行初始化
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            //根据(tab.length - 1) & hash 计算目标节点在数组中的位置
            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
            }
            //hash为-1 说明是一个forwarding nodes节点,表明正在扩容
            else if ((fh = f.hash) == MOVED)
                //帮助扩容
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                //对上面计算出来的节点进行加锁
                synchronized (f) {
                    //这里判断下有没有线程对数组进行了修改
                    if (tabAt(tab, i) == f) {
                        //这里如果hash值是大于等于0的说明是链表
                        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;
                            }
                        }
                    }
                }
                //如果链表数量大于TREEIFY_THRESHOLD(8),开始执行转换树
                if (binCount != 0) {
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        //进行元素数量统计,和决定是否扩容
        addCount(1L, binCount);
        return null;
    }

下面看下第一次put初始化数组的源码

//第一次put,初始化数组
    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
            //-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;
                        //设置下次扩容的阙值 n * 0.75
                        sc = n - (n >>> 2);
                    }
                } finally {
                    sizeCtl = sc;
                }
                break;
            }
        }
        return tab;
    }

在put的结束后 执行了一个addCount函数,主要用于统计数量以及决定是否需要扩容

private final void addCount(long x, int check) {
        CounterCell[] as; long b, s;
        //当counterCells已初始化,或者cas修改baseCount失败
        if ((as = counterCells) != null ||
            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
            CounterCell a; long v; int m;
            boolean uncontended = true;
            //当counterCells未初始化 或者 counterCells数据相应的CounterCell为null 或者
            //对相应对CounterCell的value值进行cas修改失败
            if (as == null || (m = as.length - 1) < 0 ||
                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
                !(uncontended =
                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
                //参考LongAdder的设计,比AtomicLong更高效
                fullAddCount(x, uncontended);
                return;
            }
            if (check <= 1)
                return;
            s = sumCount();
        }
        //当check>0说明新put的对象是在链表或者红黑树上,检查是否要扩容
        if (check >= 0) {
            Node<K,V>[] tab, nt; int n, sc;
            //当判断需要扩容了
            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
                   (n = tab.length) < MAXIMUM_CAPACITY) {
                //该数值是一个根据table长度计算出来的标示位,用来验证扩容是否结束
                int rs = resizeStamp(n);
                //如果为负数 说明已经有线程在扩容了
                if (sc < 0) {
                    //如果发现扩容结束了
                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
                        transferIndex <= 0)
                        break;
                    //用cas修改线程数,进入扩容阶段
                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
                        transfer(tab, nt);
                }
                //rs左移16位,将验证扩容是否结束的标示移动到高16位,低16位用于存储参与扩容的线程数
                //从2开始计数,因为1表示初始化
                //因为最高位是1,所以数值整体为负数
                else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                             (rs << RESIZE_STAMP_SHIFT) + 2))
                    transfer(tab, null);
                s = sumCount();
            }
        }
    }

下面看下扩容的思路,这一块是concurrentHashMap的精华之处
重要的参数

//cpu个数
//根据stride = (NCPU > 1) ? (n >>> 3) / NCPU : n 计算块数(bound)
//把旧的数组分成数块,每一块由一个线程负责转移数据
static final int NCPU = Runtime.getRuntime().availableProcessors();
//旧的数组
transient volatile Node<K,V>[] table;
//扩容的时候创建新的数组,大小是旧数组2倍
private transient volatile Node<K,V>[] nextTable;
//块的边界标示,当transferIndex<=0的时候标示所有的块已经分配完毕
private transient volatile int transferIndex;
//当数组某个位置的节点全部转移完毕,这个位置将会设置成ForwardingNode
static final class ForwardingNode<K,V> extends Node<K,V>

来一个图示,为了简化,所有的数值都设在假设的基础上
旧的数组容量为8
根据计算分成4块,每块有俩个节点需要处理
有3个线程参与了扩容
在这里插入图片描述
每来一个线程,就会分配一个块让线程进行处理,直到所有的块分配完毕,分配的顺序是从队尾开始 也就是从transferIndex = n 开始, 到 transferIndex<=0结束

当一个线程完成任务后,继续分配下一个块,直到所有的块分配结束

相应源码

private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
        int n = tab.length, stride;
        //NCPU是处理器数量,根据处理器数量来设置每个线程要处理的块(多个节点)
        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
            stride = MIN_TRANSFER_STRIDE; // subdivide range

        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;
        //特殊节点 hash值为MOVE -1,当put的时候遇到该节点表示正在扩容
        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;
                //检查是否所有任务已完成,如果完成了,跟新table,sizeCtl
                if (finishing) {
                    nextTable = null;
                    table = nextTab;
                    sizeCtl = (n << 1) - (n >>> 1);
                    return;
                }
                //将参与扩容的线程减1
                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
                    //如果还有其他的线程未完成任务,则本线程退出
                    if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
                        return;
                    //到这里说明应该是最后一个完成任务的线程了,设置finishing
                    finishing = advance = true;
                    i = n; // recheck before commit
                }
            }
            else if ((f = tabAt(tab, i)) == null)
                advance = casTabAt(tab, i, null, fwd);
            else if ((fh = f.hash) == MOVED)
                advance = true; // already processed
            else {
                //这里每个线程开始根据上面划分的块,处理块中的多个节点
                //处理方式和hashMap一样,分成lowNode ,highNode俩部分处理,
                //根据 (hash & 原数组长度) 判断, 如果为0则归属lowNode(保持原位置index不动)
                //否则归属highNode(位置移到 n + index)
                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);
                            //处理完之后在原位置插入特殊节点ForwardingNode,为了告诉put操作
                            //该处已被扩容,请稍后,否则put是可以正常操作的,换句话说put和transfer可以并发
                            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;
                        }
                    }
                }
            }
        }
    }

最后讲一讲size吧,官方推荐使用mappingCount,因为ConcurrentHashMap中包含的元素数量也许会超过int的最大值

public long mappingCount() {
        long n = sumCount();
        return (n < 0L) ? 0L : n; // ignore transient negative values
    }

重点在sumCount 函数上

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

最终的统计为baseCount 加上 CounterCell[]数组每一个元素的value值,继续看CounterCell

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

可以看出CounterCell只包含了一个value, 并且用到了@sun.misc.Contended
Contended的具体含义可以看@sun.misc.Contended 解决伪共享问题

还是用图示来说明
在这里插入图片描述
多个线程运行的时候,先通过cas改变baseCount值,如果成功,则该线程退出(这里和AtomicLong原理一样)
CounterCell[]数组的长度等于cpu的数量,上一步竞争baseCount失败的线程通过一定的算法用cas修改相应CounterCell的值,最大程度上避免了线程间的竞争
最终 size = baseCount + CounterCell1.value + CounterCell2.value

实际上不要盲目的相信cas带来的性能提升,cas在大量并发的情况下修改同一个变量会导致很严重的竞争和cpu资源消耗,反而降低性能,所以size的设计并没有使用AtomicLong

cas + 分段处理 才是王道

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值