ConcurrentHashMap數據結構(jdk8)

ConcurrentHashMap是1.5引入的用於高併發狀況下的檢索和更新。本文是基於jdk8的代碼進行分析的,從put方法入手,來看下該結構是如何實現的。java

1. put方法

1.1 流程

1.2 一些關鍵方法

final V putVal(K key, V value, boolean onlyIfAbsent) {
        if (key == null || value == null) throw new NullPointerException();
        //計算hash
        int hash = spread(key.hashCode());
        //默認就是0,表明鏈表的長度,若是key不碰撞都是0,
        int binCount = 0;
        //常見的自旋結構
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            //延遲加載tab,用來放Node的數組
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            //i的位置沒有值
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
                //經過cas將i位置設定爲新node
                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);
            //i位置已經有值了
            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;
                                //hash和key都相同才認爲是相同的key,而後根據onlyIfAbsent的值來決定是否覆蓋值
                                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;
                                //鏈表尾部添加新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;
                            //將k,v添加到樹中
                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                           value)) != null) {
                                oldVal = p.val;
                                if (!onlyIfAbsent)
                                    p.val = value;
                            }
                        }
                    }
                }
                if (binCount != 0) {
                    //鏈表長度大於等於8,就將其轉爲紅黑樹結構
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        //計數及擴容的代碼
        addCount(1L, binCount);
        return null;
    }
private final Node<K,V>[] initTable() {
        Node<K,V>[] tab; int sc;
        while ((tab = table) == null || tab.length == 0) {
            //sizeCtl 是tab擴容和初始化的控制器,默認是0,能夠進行操做,負的話就表明正在初始化或擴容,由於能夠多個線程擴容,-N 就表明n個線程正在擴容
            if ((sc = sizeCtl) < 0)
                Thread.yield(); // lost initialization race; just spin
            //CAS 設置 sizectl 設爲-1,失敗會跳過
            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 爲tab長度的 3/4
                        sc = n - (n >>> 2);
                    }
                } finally {
                    //此時sizeCtl 做爲長度的3/4 ,後面做爲是否須要擴容的一個判斷條件
                    sizeCtl = sc;
                }
                break;
            }
        }
        return tab;
    }
final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
        Node<K,V>[] nextTab; int sc;
        //ForwardingNode 是一個空的節點,沒有val,是當transfer時插入到頭那作標識的,因此這裏表明f 正處於transfer 狀態。
        if (tab != null && (f instanceof ForwardingNode) &&
            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
            //根據tab的長度生成個印記戳
            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的入口主要是在addCount裏面,該方法是協助transfer的入口。
                    transfer(tab, nextTab);
                    break;
                }
            }
            return nextTab;
        }
        return table;
    }
private final void addCount(long x, int check) {
        CounterCell[] as; long b, s;
        if ((as = counterCells) != null ||
            //計數器增長x,s爲最終長度
            !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();
        }
        //須要檢查是否要擴容,默認check爲0 ,每次都檢查
        if (check >= 0) {
            Node<K,V>[] tab, nt; int n, sc;
            //長度大於sizeCtl,前面說了是長度的是四分之三,而且小於最大容量2^30
            //n 爲數組長度
            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
                   (n = tab.length) < MAXIMUM_CAPACITY) {
                //待擴容列表長度n的校驗戳
                int rs = resizeStamp(n);
                //正在擴容
                if (sc < 0) {
                    // 待擴容長度n的校驗戳不一致 || 長度+1了,其餘線程擴容完了 || 超過最大的resizers || 擴容完成(transfer裏)||擴容完成(transfer裏)
                    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);
                }
                //將計算出來的校驗戳變爲sizectl的高位,2是低位,保證了上面  sc >>> RESIZE_STAMP_SHIFT) != rs 的能夠校驗長度不變化
                else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                             (rs << RESIZE_STAMP_SHIFT) + 2))
                    transfer(tab, null);
                s = sumCount();
            }
        }
    }
//擴容方法,該方法也比較長
    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
        int n = tab.length, stride;
        //stride 是每一個線程可處理的桶的數量,後面決定了nextBound的值 
        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
            stride = MIN_TRANSFER_STRIDE; // subdivide range
        //初始化nextTab 
        if (nextTab == null) {            // initiating
            try {
                @SuppressWarnings("unchecked")
                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
                //擴容爲2倍
                nextTab = nt;
            //OOM
            } catch (Throwable ex) {      // try to cope with OOME
                sizeCtl = Integer.MAX_VALUE;
                return;
            }
            nextTable = nextTab;
            //從後向前遍歷,<=0時遍歷擴容完成    
            transferIndex = n;
        }
        int nextn = nextTab.length;
        //table裏面某個位置的首節點,表明移動了,會被看成判斷條件
        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
        boolean advance = true;
        boolean finishing = false; // to ensure sweep before committing nextTab
          //bound 是邊界
        for (int i = 0, bound = 0;;) {
            Node<K,V> f; int fh;
            //獲取該線程處理的桶的邊界 以及負責向前推動下標i
            //advance 是上面操做的控制器
            while (advance) {
                int nextIndex, nextBound;
                //  向前推動下標
                if (--i >= bound || finishing)
                    advance = false;
                else if ((nextIndex = transferIndex) <= 0) {
                    i = -1;
                    advance = false;
                }
                //當前參與擴容的線程給nextindex賦值,成功的話,bound設置爲nextBound  i=transferIndex-1,跳出循環
                else if (U.compareAndSwapInt
                         (this, TRANSFERINDEX, nextIndex,
                          nextBound = (nextIndex > stride ?
                                       nextIndex - stride : 0))) {
                    bound = nextBound;
                    i = nextIndex - 1;
                    advance = false;
                }
            }
            // i=-1 是上面transferIndex<=0的條件,任務執行完畢
            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;
                    //配合上面的>=n 從新計算table和sizeCtl
                    i = n; // recheck before commit
                }
            }
            //佔位
            else if ((f = tabAt(tab, i)) == null)
                advance = casTabAt(tab, i, null, fwd);
            else if ((fh = f.hash) == MOVED)
                //該位置已經處理過,從新計算i bound等,繼續向前推動
                advance = true; // already processed
            else {
                //f是當前i位置的節點
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        Node<K,V> ln, hn;
                        //fh是f的hash值
                        //鏈表操做
                        if (fh >= 0) {
                            int runBit = fh & n;
                            Node<K,V> lastRun = f;
                             //找到鏈表中最後一個hash 相同的節點,就是最後一個節點
                            for (Node<K,V> p = f.next; p != null; p = p.next) {
                                int b = p.hash & n;
                                if (b != runBit) {
                                    runBit = b;
                                    lastRun = p;
                                }
                            }
                            //ln 猜想是low node   hn認爲是 high node ,由於會拆出來兩個鏈表
                            // hash&n ==0 一個判斷標準,符合這樣的,就做爲ln,不符合的做爲hn
                            if (runBit == 0) {
                                ln = lastRun;
                                hn = null;
                            }
                            else {
                                hn = lastRun;
                                ln = null;
                            }
                            //遍歷全部節點,符合 hash & n == 0的  就放到ln的前面,不符合的就放到hn的前面
                            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);
                            }
                            //將ln 放到nexttab的i位置,high 放到i+n位置
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            //原tab 的i位置 放fwd佔位
                            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;
                        }
                    }
                }
            }
        }
    }
相關文章
相關標籤/搜索