heima并发---ConcurrentHashMap系列后续-p6-281和以后

博客:https://www.cnblogs.com/cjsblog/p/10017911.html

博客:https://www.jianshu.com/p/865c813f2726

---

heima并发---ConcurrentHashMap系列后续-p6-281和以后_第1张图片

---

heima并发---ConcurrentHashMap系列后续-p6-281和以后_第2张图片

put方法:

   final V putVal(K key, V value, boolean onlyIfAbsent) {
        // 这里面的key和value是不能为空的
        if (key == null || value == null) throw new NullPointerException();
        // 算出hash值
        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)
                // 数组为空首先要初始化数组
                tab = initTable();
            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,扩容的
            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;
                                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;
                                if ((e = e.next) == null) {// 没有找到加到链表的尾部
                                    pred.next = new Node(hash, key,
                                                              value, null);
                                    break;
                                }
                            }
                        }
                        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;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }

代码拆分:

注意unsafe的方法:

unsafe源码:https://www.cnblogs.com/dennyzhangdd/p/7230012.html

heima并发---ConcurrentHashMap系列后续-p6-281和以后_第3张图片

注意指向的关系。

heima并发---ConcurrentHashMap系列后续-p6-281和以后_第4张图片

---

看下树化的逻辑:

private final void treeifyBin(Node[] tab, int index) {
        Node b; int n, sc;
        if (tab != null) {
            if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
                tryPresize(n << 1);
            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
                synchronized (b) {
                    if (tabAt(tab, index) == b) {// 和hashmap一样还是先改为双向链表
                        TreeNode hd = null, tl = null;
                        for (Node e = b; e != null; e = e.next) {
                            TreeNode p =
                                new TreeNode(e.hash, e.key, e.val,
                                                  null, null);
                            if ((p.prev = tl) == null)
                                hd = p;
                            else
                                tl.next = p;
                            tl = p;
                        }
                        setTabAt(tab, index, new TreeBin(hd));// 生成红黑树
                    }
                }
            }
        }
    }

注意存的是什么?

heima并发---ConcurrentHashMap系列后续-p6-281和以后_第5张图片

---

TreeBin就是一个对象,包括树的头节点。

---

初始化:

heima并发---ConcurrentHashMap系列后续-p6-281和以后_第6张图片

初始化table:https://www.jianshu.com/p/7471f98988bd

 /**
     * Initializes table, using the size recorded in sizeCtl.
     */
    private final Node[] initTable() {
        Node[] tab; int sc;
        while ((tab = table) == null || tab.length == 0) {
            if ((sc = sizeCtl) < 0)// 默认是0 初始化为-1 
                Thread.yield(); // lost initialization race; just spin
            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[] nt = (Node[])new Node[n];
                        table = tab = nt;
                        sc = n - (n >>> 2);
                    }
                } finally {
                    sizeCtl = sc;
                }
                break;
            }
        }
        return tab;
    }

---

扩容:

private final void addCount(long x, int check) {
        CounterCell[] as; long b, s;
        // 完成baseCount++的操作
        if ((as = counterCells) != null ||
            // baseCOunt增加失败
            !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[] tab, nt; int n, sc;
            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
                   (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))
                    transfer(tab, null);
                s = sumCount();
            }
        }
    }

counterCell的思路:

heima并发---ConcurrentHashMap系列后续-p6-281和以后_第7张图片

我们做下实验,看下sum就明白了:

heima并发---ConcurrentHashMap系列后续-p6-281和以后_第8张图片

cellCount:https://blog.csdn.net/chenssy/article/details/73521950,https://www.sohu.com/a/254192521_355142

https://www.jianshu.com/p/749d1b8db066

看下

// See LongAdder version for explanation
    private final void fullAddCount(long x, boolean wasUncontended) {
        int h;
        if ((h = ThreadLocalRandom.getProbe()) == 0) {
            ThreadLocalRandom.localInit();      // force initialization
            h = ThreadLocalRandom.getProbe();
            wasUncontended = true;
        }
        boolean collide = false;                // True if last slot nonempty
        for (;;) {
            CounterCell[] as; CounterCell a; int n; long v;
            if ((as = counterCells) != null && (n = as.length) > 0) {
                if ((a = as[(n - 1) & h]) == null) {
                    if (cellsBusy == 0) {            // Try to attach new Cell
                        CounterCell r = new CounterCell(x); // Optimistic create
                        if (cellsBusy == 0 &&
                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
                            boolean created = false;
                            try {               // Recheck under lock
                                CounterCell[] rs; int m, j;
                                if ((rs = counterCells) != null &&
                                    (m = rs.length) > 0 &&
                                    rs[j = (m - 1) & h] == null) {
                                    rs[j] = r;
                                    created = true;
                                }
                            } finally {
                                cellsBusy = 0;
                            }
                            if (created)
                                break;
                            continue;           // Slot is now non-empty
                        }
                    }
                    collide = false;
                }
                else if (!wasUncontended)       // CAS already known to fail
                    wasUncontended = true;      // Continue after rehash
                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
                    break;
                else if (counterCells != as || n >= NCPU)
                    collide = false;            // At max size or stale
                else if (!collide)
                    collide = true;
                else if (cellsBusy == 0 &&
                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
                    try {
                        if (counterCells == as) {// Expand table unless stale
                            CounterCell[] rs = new CounterCell[n << 1];
                            for (int i = 0; i < n; ++i)
                                rs[i] = as[i];
                            counterCells = rs;
                        }
                    } finally {
                        cellsBusy = 0;
                    }
                    collide = false;
                    continue;                   // Retry with expanded table
                }
                h = ThreadLocalRandom.advanceProbe(h);
            }
            else if (cellsBusy == 0 && counterCells == as &&
                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
                boolean init = false;
                try {                           // Initialize table
                    if (counterCells == as) {
                        CounterCell[] rs = new CounterCell[2];
                        rs[h & 1] = new CounterCell(x);
                        counterCells = rs;
                        init = true;
                    }
                } finally {
                    cellsBusy = 0;
                }
                if (init)
                    break;
            }
            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
                break;                          // Fall back on using base
        }
    }

---

什么时候扩容:https://blog.csdn.net/varyall/article/details/81277296

---

 

你可能感兴趣的:(heima并发,并发)