ConcurrentHashMap源码解析

240 阅读9分钟

重要属性

    //存放数据的node数组  用volatile修饰
    transient volatile Node<K,V>[] table;
    
    //Node 节点的特殊hash节点状态
    static final int MOVED     = -1; // hash for forwarding nodes 正在迁移的节点
    static final int TREEBIN   = -2; // hash for roots of trees 红黑树的节点
    static final int RESERVED  = -3; // hash for transient reservations
    
    //值为-1时标识正在初始化
    //扩容时为负数,低16位是2开始,随着线程增加而增加,当低16位为1时表示扩容完成,表示正有N-1个线程执行扩容操作
    //正常情况下为扩容的阈值=table.length-table.length>>2
    private transient volatile int sizeCtl;
    
    //扩容时的临时table
    private transient volatile Node<K,V>[] nextTable;
    
    //扩容时是一个槽一个槽的拆的,表示下一个要迁移的槽的索引,值为1~n之间
    private transient volatile int transferIndex;

get()

    public V get(Object key) {
        //tab就是table e指key属于槽上的头结点 eh是头结点的hashcode
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        //扰动函数  (h ^ (h >>> 16)) & HASH_BITS
        int h = spread(key.hashCode());
        //这里判断是否是空
        if ((tab = table) != null && (n = tab.length) > 0 &&
            //(n - 1) & h 取余获取key所在的下标 e为该下标下的头结点
            (e = tabAt(tab, (n - 1) & h)) != null) {
            //这里先判断头结点的hashcode是否是key的hashcode
            if ((eh = e.hash) == h) {
                //如果hashcode相同,在判断key是否相同,如果相同则返回
                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                    return e.val;
            }
            //如果头结点的hashcode小于0,说明这个槽正在扩容
            else if (eh < 0)
                return (p = e.find(h, key)) != null ? p.val : null;
            //否则沿着链表向下找,直到hashcode和key都相同的情况
            while ((e = e.next) != null) {
                if (e.hash == h &&
                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
                    return e.val;
            }
        }
        //找不到就返回null
        return null;
    }
    
    //find方法就是沿着链表走一遍,没什么好说的
        Node<K,V> find(int h, Object k) {
            Node<K,V> e = this;
            if (k != null) {
                do {
                    K ek;
                    if (e.hash == h &&
                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
                        return e;
                } while ((e = e.next) != null);
            }
            return null;
        }
    

hash在取余时h&(size-1) 如果size比较小取余时运算的生效位数只有后几位,扰动函数的作用在于增加低位的随机性
关于扰动函数的说明https://www.zhihu.com/question/28562088?sort=created

put()

final V putVal(K key, V value, boolean onlyIfAbsent) {
        //如果为空就抛出异常
        if (key == null || value == null) throw new NullPointerException();
        //获取hash
        int hash = spread(key.hashCode());
        //key所在槽下链表节点数量
        int binCount = 0;
        //开始循环
        for (Node<K,V>[] tab = table;;) {
            //f是指槽的头结点,fh是指头结点的hashCode, n是table数组的长度
            Node<K,V> f; int n, i, fh;
            //如果table为空首先初始化
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            //判断头结点是不是为null
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
                //如果头结点为null,cas把null替换成新节点并返回,这个过程是没有锁的
                if (casTabAt(tab, i, null,
                             new Node<K,V>(hash, key, value, null)))
                    break;                   // no lock when adding to empty bin
            }
            //判断头结点的hashcode是不是Moved,如果是moved说明该槽正在resize
            else if ((fh = f.hash) == MOVED)
                //帮助扩容
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                //头结点不为空也没有扩容的情况,加锁锁住头结点
                synchronized (f) {
                    //这里的tabAt采用Unsafe.getObjectVolatile来获取,也许有人质疑,直接table[index]不可以么,为什么要这么复杂?
在java内存模型中,我们已经知道每个线程都有一个工作内存,里面存储着table的副本,虽然table是volatile修饰的,但不能保证线程每次都拿到table中的最新元素,Unsafe.getObjectVolatile可以直接获取指定内存的数据,保证了每次拿到数据都是最新的。
                    if (tabAt(tab, i) == f) {
                        //判断一下hashCode是否大于0
                        if (fh >= 0) {
                            binCount = 1;
                            //沿着头结点往下走,每遍历一个节点bitCount++
                            for (Node<K,V> e = f;; ++binCount) {
                                K ek;
                                //判断node的hash和key是否相同,如果相同的话直接将value更新
                                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;
                                //如果最后一个节点是null,在后面插入一个新的节点
                                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) {
                    //判断该槽的数量是否大于等于8,如果是进行树化
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    //如果老的val不能空则返回
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        
        //记录总数,检查是否需要扩容
        addCount(1L, binCount);
        return null;
    }

initTable() 初始化

private final Node<K,V>[] initTable() {
        Node<K,V>[] tab; int sc;
        while ((tab = table) == null || tab.length == 0) {
            //sizeCtl<0 表示正在扩容或初始化,yield让出线程
            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;
                        //sizeCtl变为n的0.75倍
                        sc = n - (n >>> 2);
                    }
                } finally {
                    sizeCtl = sc;
                }
                break;
            }
        }
        return tab;
    }

addCount()

     private final void addCount(long x, int check) {
        //as类似LongAdder, s是元素总数 b是元素添加之前的总数
        CounterCell[] as; long b, s;
        if ((as = counterCells) != null ||
            //cas更新数量
            !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))) {
                fullAddCount(x, uncontended);
                return;
            }
            if (check <= 1)
                return;
                
            //获取总数
            s = sumCount();
        }
        if (check >= 0) {
            Node<K,V>[] tab, nt; int n, sc;
            //判断总数是否大于ctl
            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
                   (n = tab.length) < MAXIMUM_CAPACITY) {
                //根据length得到一个标识rs
                int rs = resizeStamp(n);
                //sc<0正在初始化
                if (sc < 0) {
                 // 如果 sc 的低 16 位不等于 标识符(校验异常 sizeCtl 变化了)
                // 如果 sc == 标识符 + 1 (扩容结束了,不再有线程进行扩容)(默认第一个线程设置 sc ==rs 左移 16 位 + 2,当第一个线程结束扩容了,就会将 sc 减一。这个时候,sc 就等于 rs + 1)
                // 如果 sc == 标识符 + 65535(帮助线程数已经达到最大)
                // 如果 nextTable == null(结束扩容了)
                // 如果 transferIndex <= 0 (转移状态变化了)
                // 结束循环 
                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
                        transferIndex <= 0)
                        break;
                    //如果可以帮助扩容,将sc+1标识一个线程帮助扩容
                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
                    //扩容
                        transfer(tab, nt);
                }
                //如果不在扩容,把SIZECTL更新,标识符左移 16 位 然后 + 2. 也就是变成一个负数。高 16 位是标识符,低 16 位初始是 2.
                else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                             (rs << RESIZE_STAMP_SHIFT) + 2))
                    //扩容
                    transfer(tab, null);
                //获取总数,循环
                s = sumCount();
            }
        }
    }

transfer()

 private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
        int n = tab.length, stride;
        //stride 每个CPU要出处理的桶的数量,槽个数的8分之一/逻辑处理器的数量,最少为16个
        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
            stride = MIN_TRANSFER_STRIDE; // subdivide range
        if (nextTab == null) {            // initiating
            try {
                @SuppressWarnings("unchecked")
                //如果临时table为空新建一个,容量为原来的两倍
                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;
            //从n开始扩容
            transferIndex = n;
        }
        
        //新数组的长度
        int nextn = nextTab.length;
        
        //扩容时的临时节点 hash为MOVED
        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
        
        boolean advance = true;
        boolean finishing = false; // to ensure sweep before committing 
        for (int i = 0, bound = 0;;) {
            Node<K,V> f; int fh;
            while (advance) {
                int nextIndex, nextBound;
                //如果完成则结束
                //从开始遍历到bound
                if (--i >= bound || finishing)
                    advance = false;
                //下一个要扩容的节点<=0结束
                else if ((nextIndex = transferIndex) <= 0) {
                    i = -1;
                    advance = false;
                }
                
                //更新transferIndex - stride
                //每当i<=bound时 i= transferIndex-1 bound - transferIndex - stride,然后从i一直迁移到bound
                else if (U.compareAndSwapInt
                         (this, TRANSFERINDEX, nextIndex,
                          nextBound = (nextIndex > stride ?
                                       nextIndex - stride : 0))) {
                    //bound本次迁移的索引范围的下限
                    bound = nextBound;
                    //i为本次迁移索引范围的上线 迁移的范围在 bound到i(第一次运行得出)
                    i = nextIndex - 1;
                    advance = false;
                }
            }
            
            //判断i是否不再迁移的范围中
            if (i < 0 || i >= n || i + n >= nextn) {
                int sc;
                //如果完成交换把nextTable赋值给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 = advance = true;
                    i = n; // recheck before commit
                }
            }
            //索引i头结点cas判断如果是null的话,cas更新把i的头结点更新成 扩容临时节点
            else if ((f = tabAt(tab, i)) == null)
                advance = casTabAt(tab, i, null, fwd);
            
            //如果判断索引i头结点不为空,并且hash == MOVED 说明这个头结点是fwd节点 已经扩容了
            else if ((fh = f.hash) == MOVED)
                advance = true; // already processed
            else {
                //给头结点加锁
                synchronized (f) {
                    //判断头结点是否变化
                    if (tabAt(tab, i) == f) {
                        //ln是原来索引的列表,hn是新索引的链表
                        Node<K,V> ln, hn;
                        if (fh >= 0) {
                            int runBit = fh & n;
                            //lastRun记录链表中最后一个节点
                            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;
                                }
                            }
                            //如果最后一个节点的runBit == 0留在原来的索引,否则索引+n
                            if (runBit == 0) {
                                ln = lastRun;
                                hn = null;
                            }
                            else {
                                hn = lastRun;
                                ln = null;
                            }
                            
                            //遍历所有节点,迁移到nextTable上
                            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);
                            //旧table的索引i值替换为fwd节点
                            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;
                        }
                    }
                }
            }
        }
    }