【Java基础】ConcurrentHashMap原理分析及应用

引言

本篇博客是基于之前的HashMap开展的,读者若是对HashMap不甚了解的话,可以参看之前的博客。
【Java基础】HashMap底层实现原理 附源码分析及面试题,让你深入Java集合
简单来说,ConcurrentHashMap是HashMap的并发版本,适合在并发环境下使用。
另外,本文关于ConcurrentHashMap的源码是基于JDK1.8的。

原理分析

ConcurrentHashMap原理:JDK1.7中,ConcurrentHashMap 采用了分段锁技术,其中 Segment是ConcurrentHashMap的内部类, 继承于 ReentrantLock。不会像 Hashtable 那样不管是 put 还是 get 操作都需要做同步处理,理论上 ConcurrentHashMap 支持 CurrencyLevel (Segment 数组数量)的线程并发。每当一个线程占用锁访问一个 Segment 时,不会影响到其他的 Segment。如下图所示:

在这里插入图片描述
但是从JDK1.8开始,ConcurrentHashMap就抛弃了原有的分段锁,而是改用CAS+synchronized来保证并发安全性。同时在JDK1.8中,也弃用了HashEntry,改用了Node(但功能相同):

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        volatile V val;
        volatile Node<K,V> next;

        Node(int hash, K key, V val, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.val = val;
            this.next = next;
        }

        public final K getKey()       { return key; }
        public final V getValue()     { return val; }
        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
        public final String toString(){ return key + "=" + val; }
        public final V setValue(V value) {
            throw new UnsupportedOperationException();
        }
        ……
  }

不难发现,valnext 都用了 volatile 修饰,保证了并发条件下的可见性。

put方法

先上源码:

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;
        /* 注释1 */
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            /* 注释2 */
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
                /* 注释3 */
            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
            }
            /* 注释4 */
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                /* 注释5 */
                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) {
                /* 注释6 */
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }
  1. 根据 key 计算出 hashCode ;
  2. 判断是否需要进行初始化;
  3. f 即为当前 key 定位出的 Node,如果为空表示当前位置可以写入数据,利用 CAS 尝试写入,失败则自旋保证成功;
  4. 如果当前位置的 hashCode == MOVED (值为-1),则需要进行扩容;
  5. 如果都不满足,则利用 synchronized 锁写入数据;
  6. 如果数量大于 TREEIFY_THRESHOLD (值为8)则要转换为红黑树。

get方法

public V get(Object key) {
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        int h = spread(key.hashCode());
        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;
    }

根据计算出来的 hashCode 寻址,如果就在桶上那么直接返回值,如果是红黑树那就按照树的方式获取值,否则就按照链表的方式遍历获取值。

参考阅读

Java并发包concurrent—ConcurrentHashMap
自旋锁与互斥锁的对比、手工实现自旋锁

发布了28 篇原创文章 · 获赞 12 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/Carson_Chu/article/details/104024192
今日推荐