ConcurrentHashMap 1.8源码解析

网上介绍ConcurrentHashMap的文章很多,我就只讲我阅读的部分笔记记录一下。

public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
        implements ConcurrentMap<K, V>, Serializable {

//put方法
final V putVal(K key, V value, boolean onlyIfAbsent) {
        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;
            // 1. 如果table为空,初始化;
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
                //2.根据hash值计算得到数组索引i,如果tab[i]为空,直接新建节点Node即可。
                if (casTabAt(tab, i, null, new Node<K, V>(hash, key, value, null)))
                    break;                   // no lock when adding to empty bin
            }
            //3.如果tab[i]不为空并且hash值为MOVED,说明该链表正在进行transfer操作,返回扩容完成后的table
            else if ((fh = f.hash) == MOVED)
                //帮助执行Transfer操作,并返回transfer后的table
                tab = helpTransfer(tab, f);
            else {
                //4.tab[i]不为空,可能是链表首节点 也可能是红黑树首节点
                V oldVal = null;
                //对首个节点进行加锁操作
                synchronized (f) {
                    if (tabAt(tab, i) == f) { //再次校验节点是否发生变更,防止并发操作
                        //4.1 链表首节点
                        if (fh >= 0) {
                            binCount = 1;
                            for (Node<K, V> e = f; ; ++binCount) {
                                K ek;
                                // 4.1.1 当前节点为所需节点,直接设置e.val = value即可。
                                if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {
                                    oldVal = e.val;
                                    if (!onlyIfAbsent) //对onlyIfAbsent支持
                                        e.val = value;
                                    break;
                                }
                                Node<K, V> pred = e;
                                //4.1.2 遍历链表
                                if ((e = e.next) == null) {
                                    //未找到值为key的节点,直接新建Node并加入链表即可。
                                    pred.next = new Node<K, V>(hash, key, value, null);
                                    break;
                                }
                            }
                        }
                        //4.2 如果首节点为TreeBin类型,说明为红黑树结构,执行putTreeVal操作。
                        else if (f instanceof TreeBin) {
                            Node<K, V> p;
                            binCount = 2; //如果当前位置已经为红黑树,则 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)
                        //1.如果tab数组长度长度小于64,直接扩容数组,不再转红黑树。
                        //2.链表需转成红黑树,
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        //检查当前容量是否需要进行扩容。
        addCount(1L, binCount);
        return null;
    }

  //初始化table
    private final Node<K, V>[] initTable() {
        Node<K, V>[] tab;
        int sc;
        while ((tab = table) == null || tab.length == 0) {
            //其他线程已经在进行初始化,当前线程只需要让出cpu片刻
            if ((sc = sizeCtl) < 0)
                Thread.yield(); // lost initialization race; just spin
            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                {//利用CAS方法把sizectl的值置为-1 表示本线程正在进行初始化
                    try {
                        if ((tab = table) == null || tab.length == 0) {
                            int n = (sc > 0) ? sc : DEFAULT_CAPACITY; //sizeCtl默认为0
                            @SuppressWarnings("unchecked")
                            Node<K, V>[] nt = (Node<K, V>[]) new Node<?, ?>[n]; //初始化tab
                            table = tab = nt;
                            //下一次扩容的大小
                            sc = n - (n >>> 2);//相当于0.75*n 设置一个扩容的阈值
                        }
                    } finally {
                        sizeCtl = sc;
                    }
                    break;
                }
            }
            //返回tab
            return tab;
        }

  //帮助执行Transfer操作
    final Node<K, V>[] helpTransfer(Node<K, V>[] tab, Node<K, V> f) {
        Node<K, V>[] nextTab;
        int sc;
        //需要帮助扩容
        if (tab != null && (f instanceof ForwardingNode) &&
                (nextTab = ((ForwardingNode<K, V>) f).nextTable) != null) {
            //扩容长度
            int rs = resizeStamp(tab.length);
            while (nextTab == nextTable && table == tab &&
                    (sc = sizeCtl) < 0) { //扩容未完成
                if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                        sc == rs + MAX_RESIZERS || transferIndex <= 0)
                    break;
                if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
                    transfer(tab, nextTab);//调用扩容方法,直接进入复制阶段
                    break;
                }
            }
            return nextTab;
        }
        return table;
    }


private final void addCount(long x, int check) {
        CounterCell[] as;
        long b, s;
        //利用CAS方法更新baseCount的值
        if ((as = counterCells) != null ||
                !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;
            while (s >= (long) (sc = sizeCtl)  //数组实际容量大于阀值
                    && (tab = table) != null && //tab数组不为空
                    (n = tab.length) < MAXIMUM_CAPACITY) { //小于最大容量
                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;
                    //已经其他线程在扩容
                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
                        transfer(tab, nt); //协助扩容
                } else if (U.compareAndSwapInt(this, SIZECTL, sc,(rs << RESIZE_STAMP_SHIFT) + 2))
                    //这里sizeCtl的初始值是一个负值=(rs<<RESIZE_STAMP_SHIFT)+2,
                    //每当一个线程参与进来执行迁移工作时,则该值进行CAS自增,
                    //该线程的任务执行完毕要退出时对该值进行CAS自减操作,
                    //所以当sizeCtl的值等于上述初值则说明了此时未有其他线程还在执行迁移工作,可以去执行收尾工作了
                    //Demo:
                    //int rs = resizeStamp(16); => rs =32795
                    //int sc = (rs << RESIZE_STAMP_SHIFT) + 2;  => rs =-2145714174
                    //int sc2 = sc >>> RESIZE_STAMP_SHIFT;  => sc2 =32795
                    transfer(tab, null); //实际扩容*2
                s = sumCount(); //获取实际容量
            }
        }
    }


private final void tryPresize(int size) {
        //计算需扩容容量
        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;
            if (tab == null || (n = tab.length) == 0) { //初始化tab
                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;
                            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);
            }
        }
    }


private final void transfer(Node<K, V>[] tab, Node<K, V>[] nextTab) {
        int n = tab.length, stride;
        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
            //计算扩容处理单元数目。
            //这里描述可能不是很清晰
            stride = MIN_TRANSFER_STRIDE; // subdivide range
        //初始化nextTab
        if (nextTab == null) {            // initiating
            try {
                //构造一个nextTable对象 它的容量是原来的两倍
                @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; //老table长度
        }
        int nextn = nextTab.length;
        //构造一个连节点指针 用于标志位
        ForwardingNode<K, V> fwd = new ForwardingNode<K, V>(nextTab);
        //并发扩容的关键属性 如果等于true 说明这个节点已经处理过
        boolean advance = true;
        boolean finishing = false; // to ensure sweep before committing nextTab
        //i表示当前处理位置
        //bound表示本次处理界限
        for (int i = 0, bound = 0; ; ) {
            Node<K, V> f;
            int fh;
            //这个while循环体的作用就是在控制i--  通过i--可以依次遍历原hash表中的节点
            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;
                //如果所有的节点都已经完成复制工作  就把nextTable赋值给table 清空临时对象nextTable
                if (finishing) {
                    nextTable = null;
                    table = nextTab;
                    //扩容阈值设置为原来容量的1.5倍  依然相当于现在容量的0.75倍
                    sizeCtl = (n << 1) - (n >>> 1);
                    return;
                }
                //利用CAS方法更新这个扩容阈值,在这里面sizectl值减一,说明当前线程参与扩容结束
                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
                }
            //如果遍历到的节点为空 则放入ForwardingNode指针
            } else if ((f = tabAt(tab, i)) == null)
                advance = casTabAt(tab, i, null, fwd);
            //如果遍历到ForwardingNode节点  说明这个点已经被处理过了 直接跳过  这里是控制并发扩容的核心
            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) { //如果fh>=0 证明这是一个Node节点
                            int runBit = fh & n; //n为原数组的长度。runBit=0 或 runBit=n(n=2^x)
                            //以下的部分在完成的工作是构造两个链表:一个顺序链表,一个开头反序结尾顺序的列表
                            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);
                            }
                            //在nextTable的i位置上插入一个链表
                            setTabAt(nextTab, i, ln);
                            //在nextTable的i+n的位置上插入另一个链表
                            setTabAt(nextTab, i + n, hn);
                            //在table的i位置上插入forwardNode节点  表示已经处理过该节点
                            setTabAt(tab, i, fwd);
                            //设置advance为true 返回到上面的while循环中 就可以执行i--操作
                            advance = true;
                        } else if (f instanceof TreeBin) {//对TreeBin对象进行处理  与上面的过程类似
                            TreeBin<K, V> t = (TreeBin<K, V>) f;
                            TreeNode<K, V> lo = null, loTail = null;  //第x为0
                            TreeNode<K, V> hi = null, hiTail = null;  //第x为1
                            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;
                                }
                            }
                            //如果扩容后已经不再需要tree的结构 反向转换为链表结构
                            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;
                            //在nextTable的i位置上插入一个链表
                            setTabAt(nextTab, i, ln);
                            //在nextTable的i+n的位置上插入另一个链表
                            setTabAt(nextTab, i + n, hn);
                            //在table的i位置上插入forwardNode节点  表示已经处理过该节点
                            setTabAt(tab, i, fwd);
                            //设置advance为true 返回到上面的while循环中 就可以执行i--操作
                            advance = true;
                        }
                    }
                }
            }
        }
    }
//当前方法主要是判断链表是否需要转成红黑树。及构造红黑树
 private final void treeifyBin(Node<K, V>[] tab, int index) {
        Node<K, V> b;
        int n, sc;
        if (tab != null) {
            //1.如果tab数组长度长度小于64,直接扩容数组,不再转红黑树。
            if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
                tryPresize(n << 1);
                //2.链表需转成红黑树
            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;
                        }
                        //将当前链表转成红黑树对象TreeBin,存放在tab的位置i上
                        setTabAt(tab, index, new TreeBin<K, V>(hd)); //树的根节点
                    }
                }
            }
        }
    }

//查找方法,比较简单
 public V get(Object key) {
        Node<K, V>[] tab;
        Node<K, V> e, p;
        int n, eh;
        K ek;
        int h = spread(key.hashCode()); //计算h
        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) {//遍历链表,查找所需key
                if (e.hash == h &&
                        ((ek = e.key) == key || (ek != null && key.equals(ek))))
                    return e.val;
            }
        }
        return null;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值