Java 杂谈JavaJava相关

ConcurrentHashMap浅析

2019-07-31  本文已影响54人  椰子奶糖
ConcurrentHashMap:在HashMap的基础上加上分段锁

底层结构

ConcurrentHashMap默认结构.png

ConcurrentHashMap的初始化:


//初始化之后的segment,会先算出ssize(算出来之后就不会改变)
//ssize就是找到大于concurrencylevel 的最小的2次方值
new segment(){
      new entry[DEFAULT_INITIAL_CAPACITY/ssize];//这个算出来一定是整除的
}

Java8中的改变


研究了一下源码
8中将segment取消了(为了兼容segment类还保留但是没用到),而是采用CAS算法,这无疑会提升效率,因为少操作一层。换句话说,8将segment和数组合二为一了。

CAS

  • 这边查出tab数组中的一个节点是空的,就会调用CAS算法U.compareAndSwapObject(...)在Unsafe类中定义,其目的是比较该元素是否为空,若为空则new一个Node放入,若不为空(但上面查出是空,则证明有别的线程干了这件事)
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
            }
  • 假如检测到这种情况,则直接break跳出循环,再执行for (Node<K,V>[] tab = table;;)此时该位置上有元素,则会跳到正常条件中执行put操作(插入或者覆盖):
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;
                }
            }

这个特性可以更加有效防止多线程死循环的情况

除此之外,判断中还有一段代码

//假如检测到扩容,则帮忙
else if ((fh = f.hash) == MOVED)    tab = helpTransfer(tab, f);

我们可以看看helpTransfer都干了啥

    /**
     * Helps transfer if a resize is in progress.
     */
    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;
    }
上一篇下一篇

猜你喜欢

热点阅读