【圖解】面試題:ConcurrentHashMap是如何保證執行緒安全的

注意:JDK1.7與JDK1.8中的ConcurrentHashMap主要延續HashMap的設計與思想,是在其基礎上進行的相應優化

1.JDK1.7中的底層實現原理
(1)JDK1.7ConcurrentHashMap的底層結構,延續HashMap的底層設計,採用數組+鏈表

(2)不同的是:ConcurrentHashMap中的數組被分為大數組和小數組,大數組是Segment,小數組是HashEntry
Segment本身是基於ReentrantLock可重入鎖來實現加鎖和釋放鎖,這樣就能保證多執行緒同時訪問ConcurrentHashMap的時候,同一時間只能有一個執行緒操作對應的節點,以此來保證執行緒安全

總結:這裡基於Segment加鎖和釋放鎖,因此稱之為分段鎖或分片鎖

在這裡插入圖片描述

2.JDK1.8中的底層實現原理
(1)JDK1.8的ConcurrentHashMap底層採用的是數組+鏈表+紅黑樹,這裡對JDK1.7進行了優化,在鏈表長度大於8並且數組長度大於64時鏈表就會轉化為紅黑樹

(2)JDK1.8中保留了Segment的定義,這僅僅是為了保證序列化時的兼容性,不再有任何結構上的用途

(3)JDK1.8中主要使用volatile+CAS或者是synchronized的方法來實現的,以此來保證執行緒安全
(i)源碼中,添加元素時,首先會判斷容器是否為空,為空,就會使用volatile加CAS來初始化
(ii)容器不為空,就會根據存儲的元素計算該位置是否為空,如果計算結果位置的結果為空,就會使用CAS來設計該節點,不為空,就會使用synchronized來加鎖實現,然後遍歷桶中的數據並且替換或者新增節點到桶中,最後判斷是否需要轉換紅黑樹

總結:JDK1.8中ConcurrentHashMap是通過對頭節點加鎖來保證執行緒安全,降低鎖粒度,發生hash衝突和加鎖的頻率也更低了

在這裡插入圖片描述
附上JDK1.8源碼

 /**
     * Maps the specified key to the specified value in this table.
     * Neither the key nor the value can be null.
     *
     * <p>The value can be retrieved by calling the {@code get} method
     * with a key that is equal to the original key.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}
     * @throws NullPointerException if the specified key or value is null
     */
    public V put(K key, V value) {
        return putVal(key, value, false);
    }

    /** Implementation for put and putIfAbsent */
    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;
            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<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 (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;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }