ConcurrentHashMap源码阅读与理解

JDK1.8 ConcurrentHashMap源码阅读与理解

几个变量:

    private static final int MAXIMUM_CAPACITY = 1 << 30;
    //最大容量 因为32位HASH的前两个字段用于控制,没有实际计算意义
    private static final int DEFAULT_CAPACITY = 16;
    //默认容量 2的幂次方,看不懂就看看HASHMAP源码吧
    static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    //最大标志位,因为有记录长度等被占用了
    private static final float LOAD_FACTOR = 0.75f;
    //扩容因子
    static final int TREEIFY_THRESHOLD = 8;
    //阈值
    static final int UNTREEIFY_THRESHOLD = 6;
    //阈值
    static final int MIN_TREEIFY_CAPACITY = 64;
    //阈值
    private static final int MIN_TRANSFER_STRIDE = 16;
    //阈值
    private static int RESIZE_STAMP_BITS = 16;
    //sizeCtl数组长度跟扩容阈值有关的比特位数
    static final int MOVED     = -1; // hash for forwarding nodes
    //moved代表该容器正在扩容中
    static final int TREEBIN   = -2; // hash for roots of trees
    //treebin代表该节点是treebin节点
    static final int RESERVED  = -3; // hash for transient reservations
    //RESERVED比较占位节点
    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
    //Hash比特位数

几个方法:
1、Put方法

    public V put(K key, V value) {
        return putVal(key, value, false);
    }
    //调用putVal()method:
    final V putVal(K key, V value, boolean onlyIfAbsent) {
        //key和value均不能等于NULL
        if (key == null || value == null) throw new NullPointerException();
        //计算Hash值
        int hash = spread(key.hashCode());
        //统计该节点有几个子节点或者是表示是treeBin节点
        int binCount = 0;
        //死循环,一种类似自旋的方式,为了多线程考虑
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            //检查table的有效性
            if (tab == null || (n = tab.length) == 0)
                //初始化table
                tab = initTable();
            //如果该节点为空则尝试插入,用CAS操作无锁的方式提高了并发量
            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
            }
            //如果该节点是转发节点,则表示该tab正在扩容
            else if ((fh = f.hash) == MOVED)
                //帮助扩容
                tab = helpTransfer(tab, f);
            //该节点有值并不是在扩容则加入插入该链表or红黑树
            else {
                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;
    }

2、扩容方法transfer:
这个方法看得我肚子饿 = =,挑关键步奏解释

    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
        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;
        //当要扩容时,会将NULL的节点放入fwd,并且将处理完成的节点设置为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;
                //检查多线程问题or是否完成
                if (--i >= bound || finishing)
                    advance = false;
                //如果transferIndex超出最大容量小于0则返回,transferIndex=tab.length
                else if ((nextIndex = transferIndex) <= 0) {
                    i = -1;
                    advance = false;
                }
                //用CAS计算得到的transferIndex  
                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*0.75
                    sizeCtl = (n << 1) - (n >>> 1);
                    return;
                }
                //CAS更新扩容阈值,sc-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
                }
            }
            else 
            //该节点为空,则插入ForwardingNode  
            if ((f = tabAt(tab, i)) == null)
                advance = casTabAt(tab, i, null, fwd);
            //该节点.hash == -1 则表示正在扩容
            else if ((fh = f.hash) == MOVED)
                advance = true; // already processed
            //如果改节点有链表or红黑树
            else {
                //锁住当前操作对象!主要通过N&hash计算是否为0分类然后决定放置的位置:high(i+N) or low(i)
                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;
                        }
                    }
                }
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值