Java JUC包源碼分析 - ConcurrentHashMap

ConcurrentHashMap之較於HashMap是保證了線程安全,其實現方式之精妙有很多值得學習的地方。同時,這篇文章也將持續更新,畢竟目前只研究了常用的幾個操作,還有其他操作,等待我去深挖。

ConcurrentHashMap主要是依靠了CAS無鎖算法和對操作的數組索引處的頭節點加鎖。

擴容操作是可以多線程協助進行,線程只要檢測到在擴容就放下當前工作去協助擴容,擴容的優先級還挺高!畢竟耗時。

ps:昨晚寫完,csdn在維護,居然無法發佈。今天剛好補充了兩個關鍵的方法進去。

public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
    implements ConcurrentMap<K,V>, Serializable {
    // 常量定義
    // 最大容量:2^30
    private static final int MAXIMUM_CAPACITY = 1 << 30;

    // 默認容量16
    private static final int DEFAULT_CAPACITY = 16;

    // 最大的數組大小
    static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    // 默認的併發大小,爲了兼容上個版本,現在沒使用
    private static final int DEFAULT_CONCURRENCY_LEVEL = 16;

    // 負載因子
    private static final float LOAD_FACTOR = 0.75f;

    // 鏈表轉樹的節點數閥值
    static final int TREEIFY_THRESHOLD = 8;

    // 從樹轉鏈表的節點樹閥值
    static final int UNTREEIFY_THRESHOLD = 6;

    // 在鏈表轉樹時table的最小容量
    static final int MIN_TREEIFY_CAPACITY = 64;

    private static final int MIN_TRANSFER_STRIDE = 16;
    private static int RESIZE_STAMP_BITS = 16;
    // 2^16-1,help resize的最大線程數
    private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
    // 32-16=16,sizeCtl中記錄size大小的偏移量
    private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;

    // Node節點hash值的幾個取值
    static final int MOVED     = -1; // 移動節點的hash值
    static final int TREEBIN   = -2; // 樹根節點的hash值
    static final int RESERVED  = -3; // 短暫保留的節點的hash值
    static final int HASH_BITS = 0x7fffffff; // 普通節點hash值可用的位

    // CPU的核數
    static final int NCPU = Runtime.getRuntime().availableProcessors();

    // 成員變量
    // 存放鍵值對的數組
    transient volatile Node<K,V>[] table;

    // 下一個要使用的table,只有在擴容時不爲null
    private transient volatile Node<K,V>[] nextTable;

    private transient volatile long baseCount;

    // 負數代表正在進行初始化或擴容操作
    // -1代表正在初始化
    // -N表示有N-1個線程正在進行擴容操作
    // 正數或0代表hash表還沒有被初始化,這個數值表示初始化或下一次進行擴容的大小,類似於擴容 
    // 閾值。它的值始終是當前ConcurrentHashMap容量的0.75倍,這與loadfactor是對應的。
    // 實際容量>=sizeCtl,則擴容。
    private transient volatile int sizeCtl;

    /**
     * The next table index (plus one) to split while resizing.
     */
    private transient volatile int transferIndex;

    /**
     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
     */
    private transient volatile int cellsBusy;

    /**
     * Table of counter cells. When non-null, size is a power of 2.
     */
    private transient volatile CounterCell[] counterCells;

    // views
    private transient KeySetView<K,V> keySet;
    private transient ValuesView<K,V> values;
    private transient EntrySetView<K,V> entrySet;

    public V put(K key, V value) {
        return putVal(key, value, false);
    }

    // 插入鍵值對,onlyIfAbsent參數是如果鍵值對已存在就不更新了。返回舊的value
    final V putVal(K key, V value, boolean onlyIfAbsent) {
        // 不允許傳入的鍵值對爲null
        if (key == null || value == null) throw new NullPointerException();
        // 計算hash值
        int hash = spread(key.hashCode());
        // 判斷是否鏈表轉樹的變量
        int binCount = 0;
        // 遍歷數組
        for (Node<K,V>[] tab = table;;) {
            // f是通過key找到的已存在的節點,n是數組長度,i是數組下標,fh是f的hash值
            Node<K,V> f; int n, i, fh;
            // 如果table還是null或者沒有元素,則初始化一個table(懶加載),然後回到上面for循環
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            // 如果計算出來的索引對應的節點f在table中還是null就以cas算法在i處新建一個node插入
            // 因爲此時還沒有加鎖,所以有可能cas失敗,失敗就重試(返回for循環);cas成功就退出
            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
            }
            // 如果索引i處的節點正處於移動狀態,也就是在擴容中,並且這個節點已經被處理過了。
            // 當前線程就先幫助擴容,等會在回到
            // for循環繼續插入值
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            // 否則就是可以在數組索引i處遍歷鏈表或樹來替換value或新建一個鏈表中的節點
            else {
                // 舊的value
                V oldVal = null;
                // 對數組i處的節點加鎖,避免多個線程同時操作數組i處的鏈表或樹。換句話說只要多個 
                // 線程操作的不是同一個數組下標的位置就可以併發執行
                synchronized (f) {
                    // 先判斷一下當前的頭節點還是不是上面計算出來的節點,畢竟在加鎖之前可能會有 
                    // 其他線程已經改了這個節點的值
                    if (tabAt(tab, i) == f) {
                    // 頭節點沒有遭到變動
                        // 如果頭節點的hash值>=0,就去遍歷鏈表
                        // 因爲樹的根節點的hash值是-2,在class TreeBin的初始化構造函數設置的
                        if (fh >= 0) {
                            // 鏈表節點個數置1,頭節點佔一個
                            binCount = 1;
                            // 遍歷鏈表
                            for (Node<K,V> e = f;; ++binCount) {
                                K ek;
                                // 如果發現key相同,則替換舊value
                                if (e.hash == hash &&
                                    ((ek = e.key) == key ||
                                     (ek != null && key.equals(ek)))) {
                                    oldVal = e.val;
                                    // 如果是onlyIfAbsent爲true,就不替換,只返回舊value
                                    if (!onlyIfAbsent)
                                        e.val = value;
                                    break;
                                }
                                Node<K,V> pred = e;
                                // 遍歷鏈表的下一個節點,如果下一個節點爲null了,說明到達鏈表 
                                // 尾部還沒有找到key相同的node,此時新建一個節點鏈接到鏈表末尾
                                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;
                            // 在紅黑樹裏操作,替換舊值或者新建node
                            // 如果不爲null,說明在樹裏找到相同的key了,返回了相應的節點
                            // 如果爲null,說明沒找到,在樹裏新插入這個節點進去
                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                           value)) != null) {
                                // 替換舊value
                                oldVal = p.val;
                                if (!onlyIfAbsent)
                                    p.val = value;
                            }
                        }
                    }
                }
                // 當進入鏈表或樹遍歷時,才binCount != 0
                if (binCount != 0) {
                    // 進入樹裏操作binCount=2,不會>=8。
                    // 所以只有進入了鏈表操作,並且鏈表節點>=8了才需要鏈表轉樹操作
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    // 返回舊值
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        // 計數器+1,因爲能執行到說明是新建了一個節點,並不是替換value
        addCount(1L, binCount);
        return null;
    }

}

接下來看下幫助擴容和擴容的實現:擴容代碼真的有點複雜,需要下更多的功夫來看懂,所以來日再更新

    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
        Node<K,V>[] nextTab; int sc;
        // ForwardingNode是一個標誌性的類,它只會出現在擴容操作期間並且bin不爲null的時候,它是 
        // 連接兩個table的標誌,ForwardingNode節點會出現在每個bin的頭節點處,指向nextTable
        if (tab != null && (f instanceof ForwardingNode) &&
            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
            // 
            int rs = resizeStamp(tab.length);
            while (nextTab == nextTable && table == tab &&
                   (sc = sizeCtl) < 0) {
                if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                    sc == rs + MAX_RESIZERS || transferIndex <= 0)
                    break;
                if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
                    transfer(tab, nextTab);
                    break;
                }
            }
            return nextTab;
        }
        return table;
    }
    
    // 把bin放到新的table裏面去,通過forwarding節點來控制多線程情況下是否跳過當前節點去擴容
    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
        int n = tab.length, stride;
        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
            stride = MIN_TRANSFER_STRIDE; // subdivide range
        // 如果是開始擴容的第一個線程到達,發現還沒開始,就新建一個兩倍容量的nextTable
        if (nextTab == null) {            // initiating
            try {
                @SuppressWarnings("unchecked")
                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
                nextTab = nt;
            } catch (Throwable ex) {      // try to cope with OOME
                sizeCtl = Integer.MAX_VALUE;
                return;
            }
            nextTable = nextTab;
            transferIndex = n;
        }
        int nextn = nextTab.length;
        // 新建標誌類頭節點,它的hash值爲-1,其他值爲null,fwd.nextTable=nextTab
        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
        // 併發擴容的關鍵屬性,等於true,說明此節點已經處理過  
        boolean advance = true;
        // 擴容完成標誌
        boolean finishing = false; // to ensure sweep before committing nextTab
        // 死循環遍歷,直到完成擴容
        for (int i = 0, bound = 0;;) {
            Node<K,V> f; int fh;
            while (advance) {
                int nextIndex, nextBound;
                if (--i >= bound || finishing)
                    advance = false;
                else if ((nextIndex = transferIndex) <= 0) {
                    i = -1;
                    advance = false;
                }
                else if (U.compareAndSwapInt
                         (this, TRANSFERINDEX, nextIndex,
                          nextBound = (nextIndex > stride ?
                                       nextIndex - stride : 0))) {
                    bound = nextBound;
                    i = nextIndex - 1;
                    advance = false;
                }
            }
            if (i < 0 || i >= n || i + n >= nextn) {
                int sc;
                if (finishing) {
                    nextTable = null;
                    table = nextTab;
                    sizeCtl = (n << 1) - (n >>> 1);
                    return;
                }
                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
                    if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
                        return;
                    finishing = advance = true;
                    i = n; // recheck before commit
                }
            }
            else if ((f = tabAt(tab, i)) == null)
                advance = casTabAt(tab, i, null, fwd);
            else if ((fh = f.hash) == MOVED)
                advance = true; // already processed
            else {
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        Node<K,V> ln, hn;
                        if (fh >= 0) {
                            int runBit = fh & n;
                            Node<K,V> lastRun = f;
                            for (Node<K,V> p = f.next; p != null; p = p.next) {
                                int b = p.hash & n;
                                if (b != runBit) {
                                    runBit = b;
                                    lastRun = p;
                                }
                            }
                            if (runBit == 0) {
                                ln = lastRun;
                                hn = null;
                            }
                            else {
                                hn = lastRun;
                                ln = null;
                            }
                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
                                int ph = p.hash; K pk = p.key; V pv = p.val;
                                if ((ph & n) == 0)
                                    ln = new Node<K,V>(ph, pk, pv, ln);
                                else
                                    hn = new Node<K,V>(ph, pk, pv, hn);
                            }
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            setTabAt(tab, i, fwd);
                            advance = true;
                        }
                        else if (f instanceof TreeBin) {
                            TreeBin<K,V> t = (TreeBin<K,V>)f;
                            TreeNode<K,V> lo = null, loTail = null;
                            TreeNode<K,V> hi = null, hiTail = null;
                            int lc = 0, hc = 0;
                            for (Node<K,V> e = t.first; e != null; e = e.next) {
                                int h = e.hash;
                                TreeNode<K,V> p = new TreeNode<K,V>
                                    (h, e.key, e.val, null, null);
                                if ((h & n) == 0) {
                                    if ((p.prev = loTail) == null)
                                        lo = p;
                                    else
                                        loTail.next = p;
                                    loTail = p;
                                    ++lc;
                                }
                                else {
                                    if ((p.prev = hiTail) == null)
                                        hi = p;
                                    else
                                        hiTail.next = p;
                                    hiTail = p;
                                    ++hc;
                                }
                            }
                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            setTabAt(tab, i, fwd);
                            advance = true;
                        }
                    }
                }
            }
        }
    }

 

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