ConcurrentHashMap源碼分析

幫忙糾錯! 誠懇感謝!

源碼分析1.8

ConcurrentHashMap數據結構是: 數組 + 鏈表 + 紅黑樹,它是線程安全的。其中拋棄了原有的 Segment 分段鎖,而採用了 CAS + synchronized 來保證併發安全性。在多併發情況下它的數據爲弱一致性的,多併發下get()返回的結果可能不是預期的值(這點在最後論證)。適用場景爲:多線程對HashMap數據添加刪除操作時。

口述運行原理:
ConcurrentHashMap是通過Node<K,V>[]數組來存儲map中的鍵值對,而每個數組位置上通過鏈表和紅黑樹的形式保存, 數組只有在第一個put時纔會初始化。
第一次添加元素的時候,默認初始值是16(DEFAULT_CAPACITY )。當往map中繼續添加元素的時候,通過hash值跟數組的長度來決定存放的那個位置((h ^ (h >>> 16)) & HASH_BITS;),如果出現放在同一個位置上,優先以鏈表的形式存放,在同一位置上個元素個超過8個以上,這時如果數組的總長度小於64(MIN_TREEIFY_CAPACITY ),則進行數組擴容,擴容到原來的兩倍大。 如果數組的長度大於等於64,那會將該節點的鏈表轉換成紅黑樹。
通過擴容的方式來把這些節點給散開,然後將這些元素複製到擴容後的數組,同一個鏈表中的元素通過hash值和數組長度來區分( int b = p.hash & n;),一部份將放到新數組的新位置上去,一部分放到新數組同樣長度的位置上,在擴容完成後,如果某個樹節點的長度小於等於6了,則會將其轉成鏈表。
其實和HashMap有多地方相似。

//  擴容新數組  n是舊數組的長度
 Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
                nextTab = nt;
private static final int MAXIMUM_CAPACITY = 1 << 30; //最大容量
private static final int DEFAULT_CAPACITY = 16;			//默認容量
static final int TREEIFY_THRESHOLD = 8;					// 變成紅黑樹的閾值
static final int UNTREEIFY_THRESHOLD = 6;				//從紅黑樹變回鏈表的閾值
static final int MIN_TREEIFY_CAPACITY = 64;				//	樹的最小容量
static final int MOVED     = -1;										 // 表示正在轉移
static final int TREEBIN   = -2; 										// 表示已經轉換成樹
static final int RESERVED  = -3; // hash for transient reservations
static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
transient volatile Node<K,V>[] table;							//默認沒初始化的數組,用來保存元素
private transient volatile Node<K,V>[] nextTable;			//轉移的時候用的數組
/**
     * 用來控制表初始化和擴容的,默認值爲0,當在初始化的時候指定了大小,這會將這個大小保存在sizeCtl中,大小爲數組的0.75
     * 當爲負的時候,說明表正在初始化或擴張,
     *     -1表示初始化
     *     -(1+n) n:表示活動的擴張線程
     */
    private transient volatile int sizeCtl;

put 方法的源碼

 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()); // 獲取hash值
        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();							// 數組初始化。之前提到的只有第一次put的時候纔會初始化數組
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {  // 根據hash值獲取下標位置  判斷位置上是否爲空
                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) {       // hash值大於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 相同直接覆蓋value值
                                    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);  //統計節點個數,檢查是否需要resize操作
        return null;
    }

// 紅黑樹的put處理方法  
final TreeNode<K,V> putTreeVal(int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                if (p == null) {
                    first = root = new TreeNode<K,V>(h, k, v, null, null);
                    break;
                }
                else if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
                    return p;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        if (((ch = p.left) != null &&
                             (q = ch.findTreeNode(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.findTreeNode(h, k, kc)) != null))
                            return q;
                    }
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    TreeNode<K,V> x, f = first;
                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
                    if (f != null)
                        f.prev = x;
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    if (!xp.red)
                        x.red = true;
                    else {
                        lockRoot();
                        try {
                            root = balanceInsertion(root, x);
                        } finally {
                            unlockRoot();
                        }
                    }
                    break;
                }
            }
            assert checkInvariants(root);
            return null;
        }

addCount分析

在put方法結尾處調用了addCount方法,把當前ConcurrentHashMap的元素個數+1這個方法一共做了兩件事,更新baseCount的值,檢測是否進行擴容。

/**
     * Adds to count, and if table is too small and not already
     * resizing, initiates transfer. If already resizing, helps
     * perform transfer if work is available.  Rechecks occupancy
     * after a transfer to see if another resize is already needed
     * because resizings are lagging additions.
     *
     * @param x the count to add
     * @param check if <0, don't check resize, if <= 1 only check if uncontended
     */
    private final void addCount(long x, int check) {
        CounterCell[] as; long b, s;
        if ((as = counterCells) != null ||
            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
            CounterCell a; long v; int m;
            boolean uncontended = true;
            if (as == null || (m = as.length - 1) < 0 ||
                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
                !(uncontended =
                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
                fullAddCount(x, uncontended);
                return;
            }
            if (check <= 1)
                return;
            s = sumCount();
        }
        if (check >= 0) {
            Node<K,V>[] tab, nt; int n, sc;
            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
                   (n = tab.length) < MAXIMUM_CAPACITY) {
                int rs = resizeStamp(n);
                if (sc < 0) {
                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
                        transferIndex <= 0)
                        break;
                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
                        transfer(tab, nt);
                }
                else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                             (rs << RESIZE_STAMP_SHIFT) + 2))
                    transfer(tab, null);
                s = sumCount();
            }
        }
    }

get源碼分析

 /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code key.equals(k)},
     * then this method returns {@code v}; otherwise it returns
     * {@code null}.  (There can be at most one such mapping.)
     *
     * @throws NullPointerException if the specified key is null
     */
    public V get(Object key) {
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        int h = spread(key.hashCode());   // 獲取hash值
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (e = tabAt(tab, (n - 1) & h)) != null) {     //各種比較不能爲空 
            if ((eh = e.hash) == h) {  //hash值比較
                if ((ek = e.key) == key || (ek != null && key.equals(ek)))  // key比較
                    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;
    }
  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;
        }

size and mappingCount 源碼解析

size方法的返回呢有意思的!
size返回的是int類型 ,int的長度有限最大就是返回到Integer.MAX_VALUE.。
mappingCount返回的就是long 類型,是實際的長度。
由於這兩個方法沒使用同步鎖機制,所以在多線程的環境下這個兩個方法不能準確的返回正確的數組長度。
這個可以自己寫一個main方法測試一下,可能後續我也會update下博客。

   /**
     * {@inheritDoc}
     */
    public int size() {
        long n = sumCount();
        return ((n < 0L) ? 0 :                           // 因爲int 類型的長度有限 這裏它個處理了一下。最大返回的就是nteger.MAX_VALUE。
                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
                (int)n);
    }
 public long mappingCount() {
        long n = sumCount();
        return (n < 0L) ? 0L : n; // ignore transient negative values   //這個方法它返回的就是實際的長度
    }

  final long sumCount() {
        CounterCell[] as = counterCells; CounterCell a;
        long sum = baseCount;
        if (as != null) {
            for (int i = 0; i < as.length; ++i) {
                if ((a = as[i]) != null)
                    sum += a.value;
            }
        }
        return sum;
    }

1.7和1.8的區別在哪裏???

跟1.7版本相比,1.8版本又有了很大的變化,已經拋棄了Segment的概念,雖然源碼裏面還保留了,也只是爲了兼容性的考慮。
1.8 在 1.7 的數據結構上做了大的改動,採用紅黑樹之後可以保證查詢效率(O(logn)),甚至取消了 ReentrantLock 改爲了 synchronized,這樣可以看出在新版的 JDK 中對 synchronized 優化是很到位的。

1.7使用的是分段鎖實現多併發的,將數組分成多個快,每個塊有自己的鎖,這樣操作A塊的時候,BCD塊不會被鎖,get和put就不會受影響。
鎖分段技術:首先將數據分成一段一段的存儲,然後給每一段數據配一把鎖,當一個線程佔用鎖訪問其中一個段數據的時候,其他段的數據也能被其他線程訪問。

1.8使用的是CAS無鎖機制,在ConcurrentHashMap中,隨處可以看到U, 大量使用了U.compareAndSwapXXX的方法,這個方法是利用一個CAS算法實現無鎖化的修改值的操作,他可以大大降低鎖代理的性能消耗。這個算法的基本思想就是不斷地去比較當前內存中的變量值與你指定的一個變量值是否相等,如果相等,則接受你指定的修改的值,否則拒絕你的操作。因爲當前線程中的值已經不是最新的值,你的修改很可能會覆蓋掉其他線程修改的結果。這一點與樂觀鎖,SVN的思想是比較類似的。
https://blog.csdn.net/bill_xiang_/article/details/81122044

HashMap 和 CoucurrrentHashMap 區別and應用場景

這裏推薦一個博客,並有代碼demo演示,get()方法到底準不準。
博客:https://blog.csdn.net/sinbadfreedom/article/details/80375048

最後在推薦一個博客:https://blog.csdn.net/programmer_at/article/details/79715177#14-table

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