ConcurrentHashMap

ConcurrentHashMap 在功能上與 HashTable 一致,都是線程安全的鍵值對容器。但是 ConcurrentHashMap 比 HashTable 有更好的併發性能:

1. HashTable 是同步的,也就是說,它的所有方法都是被 synchronized 修飾的。所以當 thread-1 進入 put 方法時,其它所有線程都不能進入 put/get 方法。這樣做可以確保線程安全,但是在高併發的場景下,效率比較低。HashTable 的代碼片段如下:

    public synchronized V put(K key, V value) {
        ...
    }
    public synchronized V get(Object key) {
        ...
    }

2. ConcurrentHashMap 對讀操作不加鎖,對寫操作部分加鎖,所以支持較高的併發。

這是 ConcurrentHashMap 的 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;
    }
    static final int spread(int h) {
        return (h ^ (h >>> 16)) & HASH_BITS;
    }
    static final int MOVED     = -1; // hash for forwarding nodes
    static final int TREEBIN   = -2; // hash for roots of trees
    static final int RESERVED  = -3; // hash for transient reservations
    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
    static class Node<K,V> implements Map.Entry<K,V> {
        ...
        /**
         * Virtualized support for map.get(); overridden in subclasses.
         */
        Node<K,V> find(int h, Object k) {
            Node<K,V> e = this;
            if (k != null) {
                do {
                    K ek;
                    if (e.hash == h &&
                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
                        return e;
                } while ((e = e.next) != null);
            }
            return null;
        }
    }

可以看出以下幾點:

    1. get 函數不是同步方法,沒有加鎖。

    2. ConcurrentHaspMap 裏面的節點有好幾種類型,可以通過 table 裏元素的key 來判斷屬於那一種。

        2.1. Node:繼承自 Map.Entry,除了 hash / key / val 之外,還有一個 next 字段。所以使用單向鏈表來解決 hash 衝突的。

        2.2. ForwardingNode:是一個標記節點,本身不保存數據,hash 值固定爲 MOVED(-1)。當 ConcurrentHaspMap 擴容時會用到這個節點。ForwardingNode 的 nextTable 字段保存了 擴容後的新節點,所以需要查找節點,就到 nextTable 中去查找。

        2.3. ReservationNode:只是一個佔位符,它用在 computeIfPresent 或者 compute 這樣的函數中。它的 find 函數直接返回 null。

        2.4. TreeBin:當 table 中的某個桶爲數時,桶裏就放 TreeBin。TreeBin 本身並不保存數據,數據是保存在 TreeNode 裏面的。TreeNode 保存 TreeNode 節點以及它們的根節點。TreeBin 持有讀寫鎖,強迫寫線程(持有鎖)必須在讀線程(不持有鎖)讀取完成之後,再進行樹的重構。(紅黑樹左旋、右旋)。

        2.5. TreeNode:TreeBin 中使用的數據節點。

這是 ConcurrentHashMap 的 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;
            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))) //  CAS 確保線程安全
                    break;                   // no lock when adding to empty bin
            }
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                synchronized (f) { // 只對 table 中的某一項加鎖。
                    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)))) { // 找到相同 key 的Entry
                                    oldVal = e.val;
                                    if (!onlyIfAbsent)
                                        e.val = value;
                                    break;
                                }
                                Node<K,V> pred = e;
                                if ((e = e.next) == null) { // key 不存在
                                    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) // bin 中訪問過的節點數 >= 8 由鏈表轉換成紅黑樹。
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }

 

 

 

參考:

1. https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章