ConCurrentHashMap(一)

一些常量:
    1. 一些特殊的hash值
      //特殊的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. sizeCtl(很有用)
    /**
     * 初始化时值为-1
     * 扩容时sizeCtl的低位为扩容线程数
     * 如果table未初始化,表示table需要初始化的大小。
     * 如果table初始化完成,表示table的容量,默认是table大小的0.75倍
     * 后续判断需要用到这个
     */
    private transient volatile int sizeCtl;
    
    
    1. 链表和树转换条件
    //桶的数量大于64时转红黑树
    static final int MIN_TREEIFY_CAPACITY = 64;
    //链表和树转换的阈值
    static final int TREEIFY_THRESHOLD = 8;
    
一些方法:

HASH_BITS = 0x7fffffff

​ 先用高16位异或然后和HASH_BITS进行&计算 ,减少碰撞

static final int spread(int h) {
    return (h ^ (h >>> 16)) & HASH_BITS;
}

​ 结果为最小的可容纳值(2的幂次),如输入18结果为32

private static final int tableSizeFor(int c) {
    int n = c - 1;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

​ 相对扩容来说,get、putVal比较简单- -

​ 先说一下,当表的长度为2的幂次时,(h % n) 和 (h & (n - 1))效果相同,以此来确定槽的位置。

public V get(Object key) {
    Node[] tab; Node e, p; int n, eh; K ek;
    //用key的hash重新散列,用来获取槽的位置
    int h = spread(key.hashCode());
    if ((tab = table) != null && (n = tab.length) > 0 &&
        //获取槽的位置
        (e = tabAt(tab, (n - 1) & h)) != null) {
        // e 为对应槽的初始Node
        if ((eh = e.hash) == h) {
            if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                return e.val;
        }
        //扩容中
        else if (eh < 0)
            //在槽中遍历查找,正在扩容所以节点为ForwardingNode,ForwardingNode中的find实际上是在扩容后的新表中进行查找
            return (p = e.find(h, key)) != null ? p.val : null;
        //在槽遍历查找
        while ((e = e.next) != null) {
            if (e.hash == h &&
                ((ek = e.key) == key || (ek != null && key.equals(ek))))
                return e.val;
        }
    }
    return null;
}

​ put实际上调用putVal

public V put(K key, V value) {
    return putVal(key, value, false);
}
final V putVal(K key, V value, boolean onlyIfAbsent) {
    if (key == null || value == null) throw new NullPointerException();
    //再次计算
    int hash = spread(key.hashCode());
    int binCount = 0;
    for (Node[] tab = table;;) {
        Node f; int n, i, fh;
        if (tab == null || (n = tab.length) == 0)
            //当前table为空则执行初始化
            tab = initTable();
        //每次循环都重新计算槽的位置(防止中途扩容导致槽位置变动)
        //f为对应槽位置的节点,i为对应槽位置,如果对应槽的位置是空的就直接cas添加
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
            if (casTabAt(tab, i, null,
                         new Node(hash, key, value, null)))
                break;                   // no lock when adding to empty bin
        }
        //MOVED = -1,ForwardingNode继承Node,只在扩容中使用,它的key,value,next全是null,hash=-1
        else if ((fh = f.hash) == MOVED)
            //帮助扩容
            tab = helpTransfer(tab, f);
        else {
            V oldVal = null;
            //同步锁
            synchronized (f) {
                //对应槽的初始节点为f则继续,否则头节点发生改变,重新循环
                if (tabAt(tab, i) == f) {
                    //是一个链表,不是树
                    if (fh >= 0) {
                        binCount = 1;
                        for (Node e = f;; ++binCount) {
                            K ek;
                            //存在相同的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 pred = e;
                            //不存在相同的key,在最后添加节点
                            if ((e = e.next) == null) {
                                pred.next = new Node(hash, key,
                                                          value, null);
                                break;
                            }
                        }
                    }
                    //为树的根节点,用树的方式添加(红黑树的根节点hash值为-2)
                    else if (f instanceof TreeBin) {
                        Node p;
                        binCount = 2;
                        if ((p = ((TreeBin)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;
            }
        }
    }
    //元素数量+1,看看要不要扩容
    addCount(1L, binCount);
    return null;
}

​ 简单的结束,transfer开始,orz 看了好久还是只有大概TAT

​ 之前说的ForwardingNode,这个只有扩容时会用到

static final class ForwardingNode extends Node {
    final Node[] nextTable;
    ForwardingNode(Node[] tab) {
        super(MOVED, null, null, null);
        this.nextTable = tab;
    }

    Node find(int h, Object k) {
        // loop to avoid arbitrarily deep recursion on forwarding nodes
        outer: for (Node[] tab = nextTable;;) {
            Node e; int n;
            if (k == null || tab == null || (n = tab.length) == 0 ||
                (e = tabAt(tab, (n - 1) & h)) == null)
                return null;
            for (;;) {
                int eh; K ek;
                if ((eh = e.hash) == h &&
                    ((ek = e.key) == k || (ek != null && k.equals(ek))))
                    return e;
                if (eh < 0) {
                    if (e instanceof ForwardingNode) {
                        tab = ((ForwardingNode)e).nextTable;
                        continue outer;
                    }
                    else
                        return e.find(h, k);
                }
                if ((e = e.next) == null)
                    return null;
            }
        }
    }
}

​ transfer

private final void transfer(Node[] tab, Node[] nextTab) {
    int n = tab.length, stride;
    //NCPU=cpu核心线程数  MIN_TRANSFER_STRIDE=16
    if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
        stride = MIN_TRANSFER_STRIDE; // subdivide range
    //如果nextTab为null,先进行一次初始化
    //外围保证第一个线程调用此方法时,参数 nextTab 为 null
    //之后参与协助的线程调用时,nextTab不会为null
    if (nextTab == null) {            // initiating
        try {
            //构造一个nextTable对象,容量为原来的两倍
            @SuppressWarnings("unchecked")
            Node[] nt = (Node[])new Node[n << 1];
            nextTab = nt;
        } catch (Throwable ex) {      // try to cope with OOME
            sizeCtl = Integer.MAX_VALUE;
            return;
        }
        //nextTable是过渡的table表,别的地方基本用不到
        nextTable = nextTab;
        transferIndex = n;
    }
    int nextn = nextTab.length;
    //构造一个节点,用于标记(之前代码中有碰到过)
    ForwardingNode fwd = new ForwardingNode(nextTab);
    //这个值为true说明节点已经处理
    boolean advance = true;
    boolean finishing = false; // to ensure sweep before committing nextTab
    //这边圈定范围
    for (int i = 0, bound = 0;;) {
        Node f; int fh;
        //一次遍历原hash表的节点
        //简单理解:i 指向了 transferIndex,bound 指向了 transferIndex-stride
        while (advance) {
            int nextIndex, nextBound;
            if (--i >= bound || finishing)
                advance = false;
            //将 transferIndex 值赋给 nextIndex
            //这里 transferIndex 一旦小于等于 0,说明原数组的所有位置都有相应的线程去处理
            else if ((nextIndex = transferIndex) <= 0) {
                i = -1;
                advance = false;
            }
            else if (U.compareAndSwapInt
                     (this, TRANSFERINDEX, nextIndex,
                      nextBound = (nextIndex > stride ?
                                   nextIndex - stride : 0))) {
                //看括号中的代码,nextBound 是这次迁移任务的边界,注意,是从后往前
                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;
            }
            //sizeCtl 在迁移前会设置为 (rs << RESIZE_STAMP_SHIFT) + 2
            //然后,每有一个线程参与迁移就会将 sizeCtl 加 1,
            //这里使用 CAS 操作对 sizeCtl 进行减 1,代表做完了属于自己的任务
            if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
                //任务结束,方法退出
                if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
                    return;
                //到这里,说明 (sc - 2) == resizeStamp(n) << RESIZE_STAMP_SHIFT,
                //也就是说,所有的迁移任务都做完了,也就会进入到上面的 if(finishing){} 分支了
                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) {
                //和putVal一样,检查节点
                if (tabAt(tab, i) == f) {
                    Node ln, hn;
                    if (fh >= 0) {
                        //下面这一块和 Java7 中的 ConcurrentHashMap 迁移是差不多的,
                        //需要将链表一分为二,
                        //找到原链表中的 lastRun,然后 lastRun 及其之后的节点是一起进行迁移的
                        //lastRun 之前的节点需要进行克隆,然后分到两个链表中
                        int runBit = fh & n;
                        Node lastRun = f;
                        for (Node 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 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(ph, pk, pv, ln);
                            else
                                hn = new Node(ph, pk, pv, hn);
                        }
                        // 其中的一个链表放在新数组的位置 i
                        setTabAt(nextTab, i, ln);
                        // 另一个链表放在新数组的位置 i+n
                        setTabAt(nextTab, i + n, hn);
                        // 将原数组该位置处设置为 fwd,代表该位置已经处理完毕,
                        // 其他线程一旦看到该位置的 hash 值为 MOVED,就不会进行迁移了
                        setTabAt(tab, i, fwd);
                        advance = true;
                    }
                    else if (f instanceof TreeBin) {
                        // 红黑树的迁移
                        TreeBin t = (TreeBin)f;
                        TreeNode lo = null, loTail = null;
                        TreeNode hi = null, hiTail = null;
                        int lc = 0, hc = 0;
                        for (Node e = t.first; e != null; e = e.next) {
                            int h = e.hash;
                            TreeNode p = new TreeNode
                                (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;
                            }
                        }
                        // 如果一分为二后,节点数少于 8,那么将红黑树转换回链表
                        ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
                            (hc != 0) ? new TreeBin(lo) : t;
                        hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
                            (lc != 0) ? new TreeBin(hi) : t;
                        // 将 ln 放置在新数组的位置 i
                        setTabAt(nextTab, i, ln);
                        // 将 hn 放置在新数组的位置 i+n
                        setTabAt(nextTab, i + n, hn);
                        // 将原数组该位置处设置为 fwd,代表该位置已经处理完毕,
                        // 其他线程一旦看到该位置的 hash 值为 MOVED,就不会进行迁移了
                        setTabAt(tab, i, fwd);
                        advance = true;
                    }
                }
            }
        }
    }
}

​ tryPresize

​ 首先只有两个地方调用了这个方法

  1. putAll(Map m) 中 tryPresize(m.size());

  2. treeifyBin(Node[] tab, int index) 中

    if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
        //这边已经扩了一倍
        tryPresize(n << 1);
    
private final void tryPresize(int size) {
    //这边再次翻倍,就是扩到了4倍,emmmm不是很理解这个
    int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
        tableSizeFor(size + (size >>> 1) + 1);
    int sc;
    while ((sc = sizeCtl) >= 0) {
        Node[] tab = table; int n;
        if (tab == null || (n = tab.length) == 0) {
            n = (sc > c) ? sc : c;
            if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                try {
                    if (table == tab) {
                        @SuppressWarnings("unchecked")
                        Node[] nt = (Node[])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[] nt;
                //这边源码错了详见
                //https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8214427
                //修正为  (sc >>> RESIZE_STAMP_SHIFT) == rs + 1 ||  (sc >>> RESIZE_STAMP_SHIFT) == rs + MAX_RESIZERS
                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);
        }
    }
}

你可能感兴趣的:(ConCurrentHashMap(一))