Java之ConcurrentHashMap源碼解析

ConcurrentHashMap源碼解析

jdk8之前的實現原理

jdk8的實現原理

JDK8的實現已經拋棄了Segment分段鎖機制,利用CAS+Synchronized來保證併發更新的安全,底層依然採用數組+鏈表+紅黑樹的存儲結構。

變量解釋

  1. table:默認爲null,初始化發生在第一次插入操作,默認大小爲16的數組,用來存儲Node節點數據,擴容時大小總是2的冪次方。

  2. nextTable:默認爲null,擴容時新生成的數組,其大小爲原數組的兩倍。

  3. sizeCtl :默認爲0,用來控制table的初始化和擴容操作,具體應用在後續會體現出來。

    • -1 代表table正在初始化
    • -N 表示有N-1個線程正在進行擴容操作
    • 其餘情況:
      • 1、如果table未初始化,表示table需要初始化的大小。
      • 2、如果table初始化完成,表示table的容量,默認是table大小的0.75倍,居然用這個公式算0.75(n - (n >>> 2))。
  4. Node:保存key,value及key的hash值的數據結構。

  5. ForwardingNode:一個特殊的Node節點,hash值爲-1,其中存儲nextTable的引用。只有table發生擴容的時候,ForwardingNode纔會發揮作用,作爲一個佔位符放在table中表示當前節點爲null或則已經被移動。

初始化

實例化ConcurrentHashMap時帶參數時,會根據參數調整table的大小,假設參數爲100,最終會調整成256,確保table的大小總是2的冪次方。

private static final int tableSizeFor(int c) {  
    int n = c - 1;  
    n |= n >>> 1;  
    n |= n >>> 2;  
    n |= n >>> 4;  
    n |= n >>> 8;  
    n |= n >>> 16;  
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;  
}  

初始化table

    private final Node<K,V>[] initTable() {  
        Node<K,V>[] tab; int sc;  
        while ((tab = table) == null || tab.length == 0) {  
        //如果一個線程發現sizeCtl<0,意味着另外的線程執行CAS操作成功,當前線程只需要讓出cpu時間片  
            if ((sc = sizeCtl) < 0)   
                Thread.yield(); // lost initialization race; just spin  
            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {  
                try {  
                    if ((tab = table) == null || tab.length == 0) {  
                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;  
                        @SuppressWarnings("unchecked")  
                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];  
                        table = tab = nt;  
                        sc = n - (n >>> 2);  
                    }  
                } finally {  
                    sizeCtl = sc;  
                }  
                break;  
            }  
        }  
        return tab;  
    }  

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;  
        for (Node<K,V>[] tab = table;;) {  
            Node<K,V> f; int n, i, fh;  
            if (tab == null || (n = tab.length) == 0)  
                tab = initTable();  
            // table中定位索引位置,n是table的大小
            // 如果f爲null,說明table中這個位置第一次插入元素,利用Unsafe.compareAndSwapObject方法插入Node節點。
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {  
                
                // 如果CAS成功,說明Node節點已經插入,隨後addCount(1L,binCout)方法會檢查當前容量是否需要進行擴容。如果CAS失敗,說明有其它線程提前插入了節點,自旋重新嘗試在這個位置插入節點。
                if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null)))  
                    break; // no lock when adding to empty bin  
            }  
            // 如果f的hash值爲-1,說明當前f是ForwardingNode節點,意味有其它線程正在擴容,則一起進行擴容操作。
            else if ((fh = f.hash) == MOVED)  
                tab = helpTransfer(tab, f);  
            //省略部分代碼  
        }  
        addCount(1L, binCount);  
        return null;  
    }  

hash算法

static final int spread(int h) {return (h ^ (h >>> 16)) & HASH_BITS;}

獲取table中對應的元素f

static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
    return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}

Doug Lea採用Unsafe.getObjectVolatile來獲取,也許有人質疑,直接table[index]不可以麼,爲什麼要這麼複雜?
在java內存模型中,我們已經知道每個線程都有一個工作內存,裏面存儲着table的副本,雖然table是volatile修飾的,但不能保證線程每次都拿到table中的最新元素,Unsafe.getObjectVolatile可以直接獲取指定內存的數據,保證了每次拿到數據都是最新的。

鏈表或紅黑樹操作

其餘情況把新的Node節點按鏈表或紅黑樹的方式插入到合適的位置,這個過程採用同步內置鎖實現併發。

synchronized (f) {
    // 在節點f上進行同步,節點插入之前,再次利用tabAt(tab, i) == f判斷,防止被其它線程修改。 
    if (tabAt(tab, i) == f) {
        // 如果f.hash >= 0,說明f是鏈表結構的頭結點,遍歷鏈表,如果找到對應的node節點,則修改value,否則在鏈表尾部加入節點。
        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類型節點,說明f是紅黑樹根節點,則在樹結構上遍歷元素,更新或增加節點。
        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;
            }
        }
    }
}
// 如果鏈表中節點數binCount >= TREEIFY_THRESHOLD(默認是8),則把鏈表轉化爲紅黑樹結構。
if (binCount != 0) {
    if (binCount >= TREEIFY_THRESHOLD)
        treeifyBin(tab, i);
    if (oldVal != null)
        return oldVal;
    break;
}

table 擴容

當table容量不足的時候,即table的元素數量達到容量閾值sizeCtl,需要對table進行擴容。

整個擴容分爲兩部分:

  1. 構建一個nextTable,大小爲table的兩倍。
  2. 把table的數據複製到nextTable中。

這兩個過程在單線程下實現很簡單,但是ConcurrentHashMap是支持併發插入的,擴容操作自然也會有併發的出現,這種情況下,第二步可以支持節點的併發複製,這樣性能自然提升不少,但實現的複雜度也上升了一個臺階。

先看第一步,構建nextTable,毫無疑問,這個過程只能只有單個線程進行nextTable的初始化,具體實現如下:

    private final void addCount(long x, int check) {  
        // 省略部分代碼  
        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操作

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章