美文网首页
Java容器之ConcurrentHashMap

Java容器之ConcurrentHashMap

作者: 进阶的小豆子 | 来源:发表于2018-08-30 12:44 被阅读0次

   HashMap在高并发场景下会产生环形链表,从而造成死循环的问题。可以改用HashTable或者Collections.synchronizedMap,但是两者都是给整个集合加锁,是非常粗粒度的同步方式,在高并发的情况下,效率比较低下。那么,既能在高并发环境下使用,又能提高运行效率,ConcurrentHashMap应运而生。

   jdk1.7之前的ConcurrentHashMap的实现是基于Segment,一个Segment类似于一个HashMap对象,Segment包含一个HashEntry数组,数组中的每一个HashEntry既是一个键值对,也是一个链表的头结点。ConcurrentHashMap内部结构示意图如下:


image

   每一个Segment都有自己的一把锁,它的put源码如下:

public V put(K key, V value) {
    Segment<K,V> s;
    if (value == null)
        throw new NullPointerException();
    //计算hash值,注意这里采用了二次哈希方法,避免哈希冲突
    int hash = hash(key.hashCode());
    //采用位运算
    int j = (hash >>> segmentShift) & segmentMask;
    if ((s = (Segment<K,V>)UNSAFE.getObject          // nonvolatile; recheck
         (segments, (j << SSHIFT) + SBASE)) == null) //  in ensureSegment
        s = ensureSegment(j);
    return s.put(key, hash, value, false);
}

   get源码如下:

public V get(Object key) {
    Segment<K,V> s; // manually integrate access methods to reduce overhead
    HashEntry<K,V>[] tab;
    //计算hash值
    int h = hash(key.hashCode());
    //采用位运算
    long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
    //定位到Segment对象
    if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
        (tab = s.table) != null) {
        for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
                 (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
             e != null; e = e.next) {
            K k;
            if ((k = e.key) == key || (e.hash == h && key.equals(k)))
                return e.value;
        }
    }
    return null;
}

   在jdk1.8之后,对于ConcurrentHashMap进行了改良。不再使用Segment,直接使用table数组保存数据,数据利用volatile保证可见性,由原来的数组+链表转换为数组+链表+红黑树。需要注意的是,jdk1.8之后锁的粒度是加在链表头上的,这是思路上的一种突破。采用CAS操作,实现无锁并发。让我们来看一下jdk1.8之后的get和put。

   get源码:

public V get(Object key) {
    Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
    //定位到table数组中
    int h = spread(key.hashCode());
    //如果该table[]存在则比较链表的头部
    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) {
            if (e.hash == h &&
                ((ek = e.key) == key || (ek != null && key.equals(ek))))
                return e.val;
        }
    }
    return null;
}

   put源码:

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<K,V>[] tab = table;;) {
        Node<K,V> f; int n, i, fh;
        //初始化table
        if (tab == null || (n = tab.length) == 0)
            tab = initTable();
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
            //利用CAS进行无锁化操作
            if (casTabAt(tab, i, null,
                         new Node<K,V>(hash, key, value, null)))
                break;                   // no lock when adding to empty bin
        }
        //如果当前节点正在扩容则帮助其扩容
        else if ((fh = f.hash) == MOVED)
            tab = helpTransfer(tab, f);
        else {
            V oldVal = null;
            //这里使用synchronized而不是ReentrantLock,jdk1.8之后对于synchronized进行了很大的优化,与ReentrantLock性能差异不大,且它可以减少内存消耗
            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;
                            }
                        }
                    }
                    //如果f是TreeBin类型的节点,证明他是红黑树结构,那么使用putTreeVal进行插入。
                    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) {
                //如果binCount大于等于TREEIFY_THRESHOLD,则变为红黑树结构
                if (binCount >= TREEIFY_THRESHOLD)
                    treeifyBin(tab, i);
                if (oldVal != null)
                    return oldVal;
                break;
            }
        }
    }
    addCount(1L, binCount);
    return null;
}

相关文章

网友评论

      本文标题:Java容器之ConcurrentHashMap

      本文链接:https://www.haomeiwen.com/subject/rdvrwftx.html