1. 程式人生 > >JAVA集合(四、ConcurrentHashMap)

JAVA集合(四、ConcurrentHashMap)

參考自:

    https://javadoop.com/post/hashmap
    https://blog.csdn.net/lsgqjh/article/details/54867107
    https://www.baidu.com/link?url=EdjLYTP4UFbVMXPGGe76qAfAFuqEIshx2_xFwZkkIcYrMXs1P5qV0Hhmx6FzJRKPuOfIRG_56hj87sttsTIK1_&wd=&eqid=8955176e000a4b31000000065b93f440
複製程式碼

閱讀之前建議先了解HashMap一文

要點總結

1.ConcurrentHashMap對節點的key和value不允許為null

2.ConcurrentHashMap是執行緒安全的,並且相對Hashtable,效率更高

3.JDK1.8中ConcurrentHashMap經過較大改動,主要利用了CAS演算法和部分synchronized實現了併發,摒棄了之前使用 Segment分段加鎖的機制

4.ConcurrentHashMap底層儲存結構同JDK1.8的HashMap一樣,都是採用了"陣列" + "連結串列" + "紅黑樹"的結構

5.計算元素存放索引的公式為(n-1)&hash,其中n為當前雜湊同table的容量,hash為元素key經過特定的雜湊運算方法獲取的

6.在JDK8(即JDK1.8)中當連結串列的長度達到8後,便會轉換為紅黑樹用於提高查詢、插入效率;

7.擴容操作類似HashMap都是達到當前容量的0.75後,翻倍擴容並進行資料遷移

8.負載因子不可以修改,固定為0.75

原始碼分析

重要屬性

    /** 預設初始容量為16。必須是2的倍數
     * The default initial table capacity.  Must be a power of 2
     * (i.e., at least 1) and at most MAXIMUM_CAPACITY.
     */
    private static final int DEFAULT_CAPACITY = 16;
    
    /** 
     *   雜湊表容量初始值和當做擴容閾值使用
     * Table initialization and resizing control.  When negative, the
     * table is being initialized or resized: -1 for initialization,
     * else -(1 + the number of active resizing threads).  Otherwise,
     * when table is null, holds the initial table size to use upon
     * creation, or 0 for default. After initialization, holds the
     * next element count value upon which to resize the table.
     */
    private transient volatile int sizeCtl;
    
    /** 
     *   雜湊表容量初始值和當做擴容閾值使用
     * Table initialization and resizing control.  When negative, the
     * table is being initialized or resized: -1 for initialization,
     * else -(1 + the number of active resizing threads).  Otherwise,
     * when table is null, holds the initial table size to use upon
     * creation, or 0 for default. After initialization, holds the
     * next element count value upon which to resize the table.
     *
     *   1.整數或者為0時,代表雜湊表陣列還沒被初始化,初始化時若sizeCtl=0,則使用DEFAULT_CAPACITY=16作為默*   認雜湊表陣列容量n,若sizeCtl>0(使用指定初始容量的建構函式),
     *   則使用sizeCtl作為雜湊表陣列容量n,然後重新賦值sizeCtl=0.75n 作為下次發生擴容的閾值
     *
     *   2.若sizeCtl=-1代表該雜湊表陣列正在進行初始化,避免多個執行緒都都進行初始化操作導致異常發生
     *   (其它執行緒判斷為-1說明有執行緒正在進行初始化操作,則不再重複操作)
     *
     *   3.負數代表正在進行擴容操作, -N代表有N-1個執行緒正在進行擴容操作
     *
     *   4.初始化和擴容後,後續sizeCtl都會賦值為0.75n作為閾值
     */
    private transient volatile int sizeCtl;
    
    /**  雜湊表陣列,用於存放每個索引的元素(可能為連結串列結構或者紅黑樹)
     * The array of bins. Lazily initialized upon first insertion.
     * Size is always a power of two. Accessed directly by iterators.
     */
    transient volatile Node<K,V>[] table;

    /** 雜湊表陣列,用於資料遷移時,建立一個原陣列2倍容量的臨時儲存區
     * The next table to use; non-null only while resizing.
     */
    private transient volatile Node<K,V>[] nextTable;
複製程式碼

建構函式

ConcurrentHashMap提供了和HashMap類似提供4種建構函式(1~4),並且提供了自己獨有的第5種建構函式:

    //1.最常用的建構函式
    ConcurrentHashMap<String,String> map = new ConcurrentHashMap<String,String>();
    
    //2.指定初始容量的建構函式
    HConcurrentHashMap<String,String> map2 = new ConcurrentHashMap<String,String>(16);
    
    //3.指定初始容量和負載因子的建構函式
    ConcurrentHashMap<String,String> map3 = new ConcurrentHashMap<String,String>(16,0.5f);
    
    //4.通過一個已存在的Map進行內容賦值的建構函式
    ConcurrentHashMap<String,String> map4 = new ConcurrentHashMap<String,String>(new ConcurrentHashMap<String,String>());
    
    //5.指定初始容量和負載因子、同時併發數目的建構函式
    ConcurrentHashMap<String,String> map5 = new ConcurrentHashMap<String,String>(16,0.5f,32);
複製程式碼

下面為原始碼的建構函式相關原始碼:

   /**
     * Creates a new, empty map with an initial table size based on
     * the given number of elements ({@code initialCapacity}), table
     * density ({@code loadFactor}), and number of concurrently
     * updating threads ({@code concurrencyLevel}).
     *
     * @param initialCapacity the initial capacity. The implementation
     * performs internal sizing to accommodate this many elements,
     * given the specified load factor.
     * @param loadFactor the load factor (table density) for
     * establishing the initial table size
     * @param concurrencyLevel the estimated number of concurrently
     * updating threads. The implementation may use this value as
     * a sizing hint.
     * @throws IllegalArgumentException if the initial capacity is
     * negative or the load factor or concurrencyLevel are
     * nonpositive
     */
    public ConcurrentHashMap(int initialCapacity,
                             float loadFactor, int concurrencyLevel) {
        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
            throw new IllegalArgumentException();
        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
            initialCapacity = concurrencyLevel;   // as estimated threads
            
        //這邊簡單來講就是將sizeCtl賦值為initialCapacity/loadFactor,並取<=MAXIMUM_CAPACITY且最接近的2^n倍的數值賦值給sizeCtl
        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
            MAXIMUM_CAPACITY : tableSizeFor((int)size);
        //根據引數設定的閾值,類似HashMap中的threshold成員變數  
        this.sizeCtl = cap;
    }
複製程式碼

Node連結串列類,實現了Map.Entry<K,V>元素介面,用於存放HashMap內容

    /**
     * Key-value entry.  This class is never exported out as a
     * user-mutable Map.Entry (i.e., one supporting setValue; see
     * MapEntry below), but can be used for read-only traversals used
     * in bulk tasks.  Subclasses of Node with a negative hash field
     * are special, and contain null keys and values (but are never
     * exported).  Otherwise, keys and vals are never null.
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        volatile V val;
        volatile Node<K,V> next;

        Node(int hash, K key, V val, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.val = val;
            this.next = next;
        }

        public final K getKey()     { return key; }
        public final V getValue()   { return val; }
        public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
        public final String toString() {
            return Helpers.mapEntryToString(key, val);
        }
        public final V setValue(V value) {
            throw new UnsupportedOperationException();
        }

        public final boolean equals(Object o) {
            Object k, v, u; Map.Entry<?,?> e;
            return ((o instanceof Map.Entry) &&
                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
                    (v = e.getValue()) != null &&
                    (k == key || k.equals(key)) &&
                    (v == (u = val) || v.equals(u)));
        }

        /**
         * 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;
        }
    }
複製程式碼

tableSizeFor函式,根據期望容量獲取雜湊桶閾值

    /**
     * 這邊的位操作最後會得到一個>=期望容量cap的最接近的2^n的值;
     * 結果會判斷是否閾值是否<0或者大於現在的最大容量2^30,,並進行修復
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
     //經過下面的 或 和位移 運算, n最終各位都是1。
        int n = cap - 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;
    }
複製程式碼

擴容

tryPresize詳解

    /**     嘗試擴容,size傳進去的時候就是翻倍的了
     * Tries to presize table to accommodate the given number of elements.
     *
     * @param size number of elements (doesn't need to be perfectly accurate)
     *  size :需要達到的容量(不必完全準確)
     */
    
    private final void tryPresize(int size) {
        //獲取最接近>=c的2^n的數值
        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
            tableSizeFor(size + (size >>> 1) + 1);
        int sc;
        //獲取閾值進行判斷 ,若 < 0則說明有其它執行緒正在初始化/擴容
        while ((sc = sizeCtl) >= 0) {
            Node<K,V>[] tab = table; int n;
            //如果當前雜湊表陣列容量為0,還沒進行初始化
            if (tab == null || (n = tab.length) == 0) {
                n = (sc > c) ? sc : c;
                //CAS操作,設定sizeCtl為-1,代表該執行緒正在擴容
                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                    try {
                        //初始化雜湊表陣列
                        if (table == tab) {
                            @SuppressWarnings("unchecked")
                            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                            table = nt;
                            //sc = n - n/2/2 = 0.75n
                            sc = n - (n >>> 2);
                        }
                    } finally {
                        //設定新的閾值
                        sizeCtl = sc;
                    }
                }
            }
            //需要改變的大小比當前閾值還低或者當前雜湊表陣列已經達到最大了,則不進行操作
            else if (c <= sc || n >= MAXIMUM_CAPACITY)
                break;
            //再原本基本上進行擴容,這邊這個==判斷,應該是為多執行緒下保險的判斷吧    
            else if (tab == table) {
                //作用不是很理解,得到一個很大的負數,https://blog.csdn.net/u011392897/article/details/60479937
                int rs = resizeStamp(n);
                //將sizeCtl設定為一個負數
                if (U.compareAndSwapInt(this, SIZECTL, sc,
                                        (rs << RESIZE_STAMP_SHIFT) + 2))
                    transfer(tab, null);
            }
        }
    }
複製程式碼

如何保障擴容操作是單執行緒完成的:

這邊使用判斷sizeCtl>0時說明沒有執行緒執行擴容,於是使用CAS操作賦值sizeCtl為-1,這樣後續執行緒判斷已經在執行擴容操作了,則不再重複執行

transfer詳解

    /**             擴容後的資料遷移
     * Moves and/or copies the nodes in each bin to new table. See
     * above for explanation.
     *
     *  tab為未擴容前的原雜湊陣列引用
     *  nextTab擴容時新生成的陣列,其大小為原陣列的兩倍。第一個擴容執行緒傳入的為null
     */
    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
        if (nextTab == null) {            // initiating
            //首個發起資料遷移的執行緒會執行這個部分,後續執行緒nextTab != null
            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;
            }
            //建立一個新的容量翻倍2n的雜湊表陣列賦給nextTable
            nextTable = nextTab;
            //賦值transferIndex為原雜湊表陣列容量n
            transferIndex = n;
        }
        //獲取新雜湊表容量,2n
        int nextn = nextTab.length;
        //建立ForwardingNode,用於舊的雜湊表陣列"佔位",並持有新表的引用
        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
        boolean advance = true;//代表可以進行下一個節點的遷移
        boolean finishing = false; // 遷移工作是否全部結束
        for (int i = 0, bound = 0;;) {
            Node<K,V> f; int fh;
            /**
            * 這邊有點難以理解,遷移工作是從原雜湊表陣列的尾部到頭部開始的。
            *
            * i: 代表需要進行遷移的雜湊表索引,在while 會被賦值為 n-1
            * bound: 遷移邊界,到這位置結束
            *
            **/
            while (advance) {
                int nextIndex, nextBound;
                //首次不符合 ,後續都符合直到遷移結束
                if (--i >= bound || finishing)
                    advance = false;
                //  nextIndex =   transferIndex = n
                else if ((nextIndex = transferIndex) <= 0) {
                    i = -1;
                    advance = false;
                }
                //一般首次進來會執行到,將 i賦值為n-1,並獲取截止的索引nextBound,
                這也是為啥說遷移是按尾部到頭部的順序進行的
                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賦值給table 
                    清空物件nextTable,以免對下次操作造成影響  
                    nextTable = null;
                    table = nextTab;
                    //擴容閾值設定為原來容量的1.5倍  依然相當於現在容量的0.75倍 (1.5n/2n=0.75) 
                    sizeCtl = (n << 1) - (n >>> 1);
                    return;
                }
                //利用CAS方法更新這個擴容閾值,在這裡面sizectl值減一,說明新加入一個執行緒參與到擴容操作  
                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
                }
            }
            //如果位置i是空的,則放入剛初始化的ForwardingNode ”空節點“ ;
            else if ((f = tabAt(tab, i)) == null)
                advance = casTabAt(tab, i, null, fwd);
            //如果該位置是ForwardingNode,代表該位置已經遷移過了; 
            else if ((fh = f.hash) == MOVED)
                advance = true; // already processed
            else {
                //鎖定頭節點
                synchronized (f) {
                    if (tabAt(tab, i) == f) {//雙重判斷,和單例模式的雙重判斷類似
                        Node<K,V> ln, hn;
                        //頭結點的hash>0,說明該位置是連結串列結構
                        if (fh >= 0) {
                            /** 
                              *下面這一塊和 JDK1.7 中的 ConcurrentHashMap 遷移是差不多的,
                              * 需要將連結串列一分為二,
                              * 找到原連結串列中的 lastRun,然後 lastRun 及其之後的節點是一起進行遷移的
                              * 這樣就不需要一個個判斷連結串列中的節點進行計算新位置並遷移
                              * ln,hn分別為舊位置的低索引,新位置的高索引(實際應用過程,這樣子效率較高)
                              **/
                            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);
                            }
                            //將原連結串列資料遷移到新雜湊表陣列
                           (從i位置遷移過來,節點可能在新雜湊表陣列的索引i或者i+n的位置,可檢視HashMap擴容說明)
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            //將原雜湊表該i位置設定為ForwardingNode ”空節點“
                            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;
                        }
                    }
                }
            }
        }
    }
複製程式碼

多執行緒是如何協作完成資料遷移的: 在transfer有一個判斷 if ((fh = f.hash) == MOVED),如果遍歷到的節點是forward節點,就向後繼續遍歷,再加上給節點上鎖的機制,就完成了多執行緒的控制。多執行緒遍歷節點,處理了一個節點,就把對應點的值set為forward,另一個執行緒看到forward,就向後遍歷。這樣交叉就完成了複製工作。而且還很好的解決了執行緒安全的問題。

helpTransfer詳解

    /**
     * Helps transfer if a resize is in progress.
     */
    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
        Node<K,V>[] nextTab; int sc;
        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;
    }
複製程式碼

這是一個協助擴容的方法。這個方法被呼叫的時候,當前ConcurrentHashMap一定已經有了nextTable物件,首先拿到這個nextTable物件,呼叫transfer方法。回看上面的transfer方法可以看到,當本執行緒進入擴容方法的時候會直接進入複製階段。

增加、修改

1.put(k,v)方法,往雜湊表中新增或者覆蓋更新對應key的元素,呼叫putVal實現

public V put(K key, V value) {
    return putVal(key, value, false); //putVal和HashMap相比少了一個引數
}
複製程式碼

2.putIfAbsent(k,v)方法(JDK8才新增的API),往雜湊表中新增key對應的新元素,若原本已存在key對應的元素則不進行更新,呼叫putVal實現

public V putIfAbsent(K key, V value) {
    return putVal(key, value, true);
}
複製程式碼

3.replace(k,v)方法(JDK8才新增的方法),替換key對應元素的value值,不存在不替換(內部還是呼叫了put)

    /**
     * {@inheritDoc}
     *
     * @return the previous value associated with the specified key,
     *         or {@code null} if there was no mapping for the key
     * @throws NullPointerException if the specified key or value is null
     */
    public V replace(K key, V value) {
        if (key == null || value == null)
            throw new NullPointerException();
        return replaceNode(key, value, null);
    }
複製程式碼

4.replace(K key, V oldValue, V newValue) ,若存在key對應的元素且value相等於oldValue則將其替換為newValue

    /**
     * {@inheritDoc}
     *
     * @throws NullPointerException if any of the arguments are null
     */
    public boolean replace(K key, V oldValue, V newValue) {
        if (key == null || oldValue == null || newValue == null)
            throw new NullPointerException();
        return replaceNode(key, newValue, oldValue) != null;
    }
複製程式碼

5.putAll(Map<? extends K, ? extends V> m),將m中存在的元素全部新增進雜湊表

/**
 * Copies all of the mappings from the specified map to this one.
 * These mappings replace any mappings that this map had for any of the
 * keys currently in the specified map.
 *
 * @param m mappings to be stored in this map
 */
public void putAll(Map<? extends K, ? extends V> m) {
    tryPresize(m.size());
    for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
        putVal(e.getKey(), e.getValue(), false);
}
複製程式碼

putVal詳解


    //實際實現put和putIfAbsent的介面
    /** Implementation for put and putIfAbsent */
    final V putVal(K key, V value, boolean onlyIfAbsent) {
        //不允許key和value為Null
        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();
            //CAS操作,找到該元素key hash對應的
            的雜湊表陣列下標(n - 1) & hash,獲取該位置的第一個節點f    
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
                //如果該陣列位置為空,CAS操作建立一個新的元素節點存入該位置
                if (casTabAt(tab, i, null,
                             new Node<K,V>(hash, key, value, null)))
                    break;                   // no lock when adding to empty bin
            }
            //如果當前正在擴容,( 擴容時hash會為賦值為MOVE)
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            //這邊代表該陣列下標位置對應的第一個節點元素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) {
                                //如果該元素與要新增的新元素key一致,處理是否更新,退出迴圈
                                K ek;
                                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;
                                //獲取該連結串列的下一個元素,進行判斷
                                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;
                            }
                        }
                        else if (f instanceof ReservationNode) //保留節點
                            throw new IllegalStateException("Recursive update");
                    }
                }
                //判斷當前連結串列元素個數
                if (binCount != 0) {
                    // 判斷是否要將連結串列轉換為紅黑樹,臨界值和 HashMap 一樣,也是 8
                    if (binCount >= TREEIFY_THRESHOLD)
                        //該方法和hashmap有點不同,就是該方法不一定會進行紅黑樹轉換,
                        如果當前陣列的長度小於 64,那麼會選擇進行陣列擴容,而不是轉換為紅黑樹
                        treeifyBin(tab, i); 
                    if (oldVal != null)
                        return oldVal; //put操作返回old value
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }
複製程式碼

spread詳解

    /*
     * Encodings for Node hash fields. See above for explanation.
     */
    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
    
    /**
     * Spreads (XORs) higher bits of hash to lower and also forces top
     * bit to 0. Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
     static final int spread(int h) {
        return (h ^ (h >>> 16)) & HASH_BITS;
     }
複製程式碼

initTable詳解

/** 用於使用sizeCtl建立並初始化雜湊表容量
 * Initializes table, using the size recorded in sizeCtl.
 */
private final Node<K,V>[] initTable() {
    Node<K,V>[] tab; int sc;
    while ((tab = table) == null || tab.length == 0) {
        //將sc賦值為sizeCtl,獲取初始容量,這邊如果小於0說明已經存在其他執行緒正在執行初始化操作了
        if ((sc = sizeCtl) < 0)
            Thread.yield(); // lost initialization race; just spin   通知讓出cpu時間片讓其他執行緒執行
        //執行CAS操作,硬體級別的原子操作,作用是將 sizeCtl賦值為-1,代表該執行緒搶到了鎖
        else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
            try {
                if ((tab = table) == null || tab.length == 0) {
                    //未呼叫建構函式賦值初始容量的,則使用預設容量DEFAULT_CAPACITY==16,否則使用計算好的sizeCtl
                    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/2 = 0.75n
                    sc = n - (n >>> 2);
                }
            } finally {
                //重新賦值sizeCtl , 下次存入的元素達到容量值的0.75的時候將發生擴容
                sizeCtl = sc;
            }
            break;
        }
    }
    return tab;
}
複製程式碼

treeifyBin詳解

/**     連結串列轉紅黑樹
 * Replaces all linked nodes in bin at given index unless table is
 * too small, in which case resizes instead.
 */
 //tab:當前存放所有資料的雜湊表陣列 ; index:需要判斷是否轉換為紅黑樹的陣列索引下標
private final void treeifyBin(Node<K,V>[] tab, int index) {
    Node<K,V> b; int n;
    if (tab != null) {
        //如果當前雜湊表陣列長度小於MIN_TREEIFY_CAPACITY(64)時,進行陣列擴容
        if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
            tryPresize(n << 1);
        else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
            //獲取頭結點加鎖
            synchronized (b) {
                if (tabAt(tab, index) == b) {
                    TreeNode<K,V> hd = null, tl = null;
                    //轉換為紅黑樹
                    for (Node<K,V> e = b; e != null; e = e.next) {
                        TreeNode<K,V> p =
                            new TreeNode<K,V>(e.hash, e.key, e.val,
                                              null, null);
                        if ((p.prev = tl) == null)
                            hd = p;
                        else
                            tl.next = p;
                        tl = p;
                    }
                    //將紅黑樹存在到該陣列索引位置
                    setTabAt(tab, index, new TreeBin<K,V>(hd));
                }
            }
        }
    }
}
複製程式碼

addCount詳解

/**  更新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;
    //利用CAS方法更新baseCount的值   
    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();
    }
    //如果check值大於等於0 則需要檢驗是否需要進行擴容操作
    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);
            }
            //當前執行緒是唯一的或是第一個發起擴容的執行緒  此時nextTable=null  
            else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                         (rs << RESIZE_STAMP_SHIFT) + 2))
                transfer(tab, null);
            s = sumCount();
        }
    }
}
複製程式碼

replaceNode詳解

    /**
     * Implementation for the four public remove/replace methods:
     * Replaces node value with v, conditional upon match of cv if
     * non-null.  If resulting value is null, delete.
     */
    final V replaceNode(Object key, V value, Object cv) {
        //獲取該key對應的hash
        int hash = spread(key.hashCode());
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            //如果不存在對應key的節點則結束
            if (tab == null || (n = tab.length) == 0 ||
                (f = tabAt(tab, i = (n - 1) & hash)) == null)
                break;
            //當前正在擴容  
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                boolean validated = false;
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        //連結串列結構
                        if (fh >= 0) {
                            validated = true;
                            for (Node<K,V> e = f, pred = null;;) {
                                K ek;
                                //如果找到了Key對應節點
                                if (e.hash == hash &&
                                    ((ek = e.key) == key ||
                                     (ek != null && key.equals(ek)))) {
                                    V ev = e.val;
                                    //判斷cv==null,或者cv符合節點value指向刪除操作
                                    if (cv == null || cv == ev ||
                                        (ev != null && cv.equals(ev))) {
                                        oldVal = ev;
                                        if (value != null)
                                            e.val = value;
                                        //找到要刪除的節點,非首節點,更新前節點指向後節點    
                                        else if (pred != null)
                                            pred.next = e.next;
                                        //如果該首節點f就是要刪除的節點,將數字i位置指向f.next    
                                        else
                                            setTabAt(tab, i, e.next);
                                    }
                                    break;
                                }
                                pred = e;
                                if ((e = e.next) == null)
                                    break;
                            }
                        }
                        //紅黑樹結構的刪除操作
                        else if (f instanceof TreeBin) {
                            validated = true;
                            TreeBin<K,V> t = (TreeBin<K,V>)f;
                            TreeNode<K,V> r, p;
                            if ((r = t.root) != null &&
                                (p = r.findTreeNode(hash, key, null)) != null) {
                                V pv = p.val;
                                if (cv == null || cv == pv ||
                                    (pv != null && cv.equals(pv))) {
                                    oldVal = pv;
                                    if (value != null)
                                        p.val = value;
                                    else if (t.removeTreeNode(p))
                                        setTabAt(tab, i, untreeify(t.first));
                                }
                            }
                        }
                        else if (f instanceof ReservationNode)
                            throw new IllegalStateException("Recursive update");
                    }
                }
                if (validated) {
                    if (oldVal != null) {
                        if (value == null)
                            addCount(-1L, -1);//更新刪除一個節點
                        //操作成功返回舊value
                        return oldVal;
                    }
                    break;
                }
            }
        }
        return null;
    }
複製程式碼

刪除 (檢視replaceNode方法)

1.remove(k)方法,從雜湊表中移除指定key對應的元素

    public V remove(Object key) {
        return replaceNode(key, null, null);
    }
複製程式碼

2.remove(k,v)方法,從雜湊表中移除指定key並且value匹配對應的元素

    public V replace(K key, V value) {
        if (key == null || value == null)
            throw new NullPointerException();
        return replaceNode(key, value, null);
    }
複製程式碼

3.remove(k,oldValue,newValue)方法,從雜湊表中移除指定key並且value匹配對應的元素

   public boolean replace(K key, V oldValue, V newValue) {
        if (key == null || oldValue == null || newValue == null)
            throw new NullPointerException();
        return replaceNode(key, newValue, oldValue) != null;
    }
複製程式碼

2.clear方法,清空雜湊表的所有元素

    public void clear() {
        long delta = 0L; // negative number of deletions
        int i = 0;
        Node<K,V>[] tab = table;
        while (tab != null && i < tab.length) {
            int fh;
            Node<K,V> f = tabAt(tab, i);
            if (f == null)
                ++i;
            else if ((fh = f.hash) == MOVED) {
                tab = helpTransfer(tab, f);
                i = 0; // restart
            }
            else {
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        Node<K,V> p = (fh >= 0 ? f :
                                       (f instanceof TreeBin) ?
                                       ((TreeBin<K,V>)f).first : null);
                        while (p != null) {
                            --delta;
                            p = p.next;
                        }
                        setTabAt(tab, i++, null);
                    }
                }
            }
        }
        if (delta != 0L)
            addCount(delta, -1);
    }
複製程式碼

查詢

1.get方法,獲取指定key對應元素的Value,存放則返回value,否則返回null

get過程操作如下: 1.計算該key對應的hash值,確認該key位於雜湊表陣列的索引值:(n - 1) & h

2.獲取該索引值的位置對應的首節點資訊,若首節點不為空,則接著往下判斷,否則返回Null

3.判讀首個節點是否就是要找的節點,若是,則返回value結束查詢

4.判斷首個節點的hash值是否小於0,若是則說明該位置為紅黑樹,或者正在擴容,執行find操作

5.否則該位置為連結串列結構,遍歷連結串列判斷是否存在符合的節點

    public V get(Object key) {
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        //計算key對應hash
        int h = spread(key.hashCode());
        //判斷雜湊表陣列不為空,並且獲取並判斷該key對應的位置節點不為空
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (e = tabAt(tab, (n - 1) & h)) != null) {
            //如果該連結串列首節點為索要查詢的節點,返回value
            if ((eh = e.hash) == h) {
                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                    return e.val;
            }
            //如果該連結串列首節點的hash值<0,說明是紅黑樹或者正在擴容
            else if (eh < 0)
                return (p = e.find(h, key)) != null ? p.val : null;
            //迴圈遍歷該連結串列,判讀是否存在與key對應的節點    
            while ((e = e.next) != null) {
                if (e.hash == h &&
                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
                    return e.val;
            }
        }
        return null;
    }
複製程式碼

2.getOrDefault(K key,V defaultValue),JDK8提供的方法,獲取指定key對應的元素value,存在則返回對應的value,否則返回defaultValue

    public V getOrDefault(Object key, V defaultValue) {
        V v;
        return (v = get(key)) == null ? defaultValue : v;
    }
複製程式碼

3.containsKey方法,判斷雜湊表中所有key項是否包含該key,存在返回true,不存在返回false

    public boolean containsKey(Object key) {
        return get(key) != null;
    }
複製程式碼

3.containsValue方法,判斷雜湊表中所有value項中是否包含該value,存在返回true,不存在返回false,原始碼上看就是所有節點遍歷過去,遇到存在value相等則停止

    public boolean containsValue(Object value) {
        if (value == null)
            throw new NullPointerException();
        Node<K,V>[] t;
        if ((t = table) != null) {
            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
            for (Node<K,V> p; (p = it.advance()) != null; ) {
                V v;
                if ((v = p.val) == value || (v != null && value.equals(v)))
                    return true;
            }
        }
        return false;
    }
複製程式碼

關注微信公眾號,共同進步