天天看點

7 ConcurrentHashMap 源碼注釋1

public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
    implements ConcurrentMap<K,V>, Serializable {
    private static final long serialVersionUID = 7249069246763182397L;

/* ---------------- Constants -------------- */

    /**
     * table 的最大長度。這個值必須恰好是1<<30,才能保持在Java數組配置設定和索引範圍内
     * table的大小為2的幂,而且還需要這樣做,因為32位哈希字段的前兩位用于控制目的。
     * The largest possible table capacity.  This value must be
     * exactly 1<<30 to stay within Java array allocation and indexing
     * bounds for power of two table sizes, and is further required
     * because the top two bits of 32bit hash fields are used for
     * control purposes.
     */
    // int 的最大值是 1 << 31 -1, 而table的長度必須是2 的幂,是以最大值隻能是 1 << 30
    // 32位哈希字段的前兩位用于控制目的?
    //       -> 當 table的長度由 1 << 29 (第30位是1) 擴容到 1 << 30時, 判斷的是hash值的第30位的值,
    // 擴容到 1 << 30後,不會再進行擴容,是以,hash值的第31 和 32位對元素在table中的分布永遠不會有
    // 任何的影響,是以最适合用于控制目的
    private static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * table 的預設初始容量。必須是2的幂(即,至少1)和最大 MAXIMUM_CAPACITY。
     * 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;

    /**
     * 數組的最大長度。
     * The largest possible (non-power of two) array size.
     * Needed by toArray and related methods.
     */
    // 一些vm在數組中保留一些頭資訊。試圖配置設定更大的數組可能會導緻OutOfMemoryError:請求的數組大小超過VM限制
    static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * table 的預設并發級别。未使用,但為與該類以前的版本相容而定義。
     * The default concurrency level for this table. Unused but
     * defined for compatibility with previous versions of this class.
     */
    private static final int DEFAULT_CONCURRENCY_LEVEL = 16;

    /**
     * table 的負載因子。在構造函數中重寫此值隻會影響初始表容量。
     * The load factor for this table. Overrides of this value in
     * constructors affect only the initial table capacity.
     * 通常不使用實際的浮點值。對于相關的調整門檻值,使用{@code n - (n >>> 2)}等表達式更為簡單。
     * The actual floating point value isn't normally used -- it is
     * simpler to use expressions such as {@code n - (n >>> 2)} for
     * the associated resizing threshold.
     */
    private static final float LOAD_FACTOR = 0.75f;

    /**
     * 使用tree而不是list的容器計數門檻值。
     * The bin count threshold for using a tree rather than list for a
     * 當向至少有這麼多節點的bin中添加元素時,bin将被轉換為樹。
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes.
     * 該值必須大于2,并且應該至少為8,以便與tree移除時關于收縮後轉換回普通bin的假設相吻合。
     * The value must be greater
     * than 2, and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * 重新調整大小時,當元素個數小于這個門檻值,将紅黑樹轉成連結清單
     * The bin count threshold for untreeifying a (split) bin during a
     *                  必須小于TREEIFY_THRESHOLD
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 連結清單轉成紅黑樹時,table的最小size,否則隻會對 table進行擴容
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
     * conflicts between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

    /**
     * 每個轉移步驟的最少rebinnings。範圍被細分以允許多個調整大小的線程。
     * Minimum number of rebinnings per transfer step. Ranges are
     * subdivided to allow multiple resizer threads.
     * 此值用作下限,以避免resizers遇到過多的記憶體争用。
     * This value serves as a lower bound to avoid resizers encountering
     * excessive memory contention.  The value should be at least
     * DEFAULT_CAPACITY.
     */
    private static final int MIN_TRANSFER_STRIDE = 16;

    /**
     * 用于生成stamp的位數。
     * The number of bits used for generation stamp in sizeCtl.
     * Must be at least 6 for 32bit arrays.
     */
    private static int RESIZE_STAMP_BITS = 16;

    /**
     * 可以幫助調整大小的最大線程數。
     * The maximum number of threads that can help resize.
     * Must fit in 32 - RESIZE_STAMP_BITS bits.
     */
    // RESIZE_STAMP_BITS = 16  ->  (1 << 16) - 1 = 65535
    private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;

    /**
     * 用于在sizeCtl中記錄大小戳的位移位。
     * The bit shift for recording size stamp in sizeCtl.
     */
    // RESIZE_STAMP_BITS = 16;   RESIZE_STAMP_SHIFT = 32 - 16 = 16;
    private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;

    /*
     * 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
    // ReservationNode 使用的,computeIfAbsent()和compute()中占位使用的
    static final int RESERVED  = -3; // hash for transient reservations
    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash

    /** Number of CPUS, to place bounds on some sizings */
    static final int NCPU = Runtime.getRuntime().availableProcessors();

    /** For serialization compatibility. */
    private static final ObjectStreamField[] serialPersistentFields = {
        new ObjectStreamField("segments", Segment[].class),
        new ObjectStreamField("segmentMask", Integer.TYPE),
        new ObjectStreamField("segmentShift", Integer.TYPE)
    };

    /* ---------------- Nodes -------------- */

    /**
     * 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;

        // ForwardingNode 傳入 (MOVED, null, null, null)
        // TreeBin 傳入 TREEBIN, null, null, null
        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 key + "=" + val; }

        // ConcurrentHashMap的更新操作需要擷取鎖,是以不支援直接修改值
        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;
        }
    }

    /* ---------------- Static utilities -------------- */

    /**
     * 将(XORs)較高的散列位傳播到較低的散列,并将最高位強制為0。
     * Spreads (XORs) higher bits of hash to lower and also forces top
     *          由于該表使用了power-of-two掩碼,是以僅在目前掩碼之上的位上變化的散列集總是會發生沖突。
     * bit to 0. Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     *                  (已知的例子包括一組在小表中儲存連續整數的浮點key。)
     * 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),
     * 因為我們用樹來處理箱子裡的大量的碰撞,我們隻是用最便宜的方式來XOR一些移位的位來減少系統的丢失,
     * 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) {
        // (h ^ (h >>> 16)) 高16位不變,低16位取高16位與低16位 異或後的值
        // HASH_BITS = 0x7fffffff.     & HASH_BITS 的作用是,将最高位置為 0
        return (h ^ (h >>> 16)) & HASH_BITS;
    }

    /**
     * Returns a power of two table size for the given desired capacity.
     * See Hackers Delight, sec 3.2
     */
    // 傳回大于等于c的最小的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;
    }

    /**
     * Returns x's Class if it is of the form "class C implements
     * Comparable<C>", else null.
     */
    // 判斷x的類是否是 "class C implements Comparable<C>" 類型的
    static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
            // c = x.getClass(), 并判斷c是否是 String.class
            if ((c = x.getClass()) == String.class) // bypass checks
                // 如果是字元串,則通過檢查
                return c;

            if ((ts = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType)t).getRawType() ==
                         Comparable.class) &&
                        (as = p.getActualTypeArguments()) != null &&
                        as.length == 1 && as[0] == c) // type arg is c
                        // p.getActualTypeArguments() 擷取泛型類型
                        return c;
                }
            }
        }
        return null;
    }

    /**
     * Returns k.compareTo(x) if x matches kc (k's screened comparable
     * class), else 0.
     */
    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }

    /* ---------------- Table element access -------------- */

    /*
     * Volatile access methods are used for table elements as well as
     * elements of in-progress next table while resizing.  All uses of
     * the tab arguments must be null checked by callers.  All callers
     * also paranoically precheck that tab's length is not zero (or an
     * equivalent check), thus ensuring that any index argument taking
     * the form of a hash value anded with (length - 1) is a valid
     * index.  Note that, to be correct wrt arbitrary concurrency
     * errors by users, these checks must operate on local variables,
     * which accounts for some odd-looking inline assignments below.
     * Note that calls to setTabAt always occur within locked regions,
     * and so in principle require only release ordering, not
     * full volatile semantics, but are currently coded as volatile
     * writes to be conservative.
     */

    @SuppressWarnings("unchecked")
    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
        // (long)i << ASHIFT) + ABASE -> 索引i 的位址偏移量
        // 從給定的Java變量中擷取一個具有volatile讀取語義的引用值
        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
    }

    // c -> expected
    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
                                        Node<K,V> c, Node<K,V> v) {
        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
    }

    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
    }

    /* ---------------- Fields -------------- */

    /**
     * 在第一次插入時惰性初始化。
     * The array of bins. Lazily initialized upon first insertion.
     * 大小總是二的幂。由疊代器直接通路。
     * Size is always a power of two. Accessed directly by iterators.
     */
    // table 使用 volatile 修飾了
    transient volatile Node<K,V>[] table;

    /**
     * 隻有在擴容的時候是非空的
     * The next table to use; non-null only while resizing.
     */
    private transient volatile Node<K,V>[] nextTable;

    /**
     * 基本計數器值,主要在沒有争用時使用,但也可作為表初始化競争期間的回退。
     * Base counter value, used mainly when there is no contention,
     * but also as a fallback during table initialization
     * races. Updated via CAS.      通過CAS更新
     */
    private transient volatile long baseCount;

    /**
     * 表初始化和大小調整控件。當為負值時,表被初始化或調整大小:-1表示初始化,否則-(1 +活動調整大小的線程數)。
     * 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,
     * 否則,當表為空時,保留建立時使用的初始表大小,預設為0。
     * when table is null, holds the initial table size to use upon
     *              初始化之後,儲存下一個元素count值,根據該值調整表的大小。
     * creation, or 0 for default. After initialization, holds the
     * next element count value upon which to resize the table.
     */
    private transient volatile int sizeCtl;

    /**
     * 調整大小時要分割的下一個表索引(加上一個)。
     * The next table index (plus one) to split while resizing.
     */
    private transient volatile int transferIndex;

    /**
     * 自旋鎖(通過CAS來擷取鎖),CounterCells 建立、擴容的時候使用
     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
     */
    private transient volatile int cellsBusy;

    /**
     *                          非空的時候大小為 2的幂
     * 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 operations -------------- */

    /**
     * Creates a new, empty map with the default initial table size (16).
     */
    public ConcurrentHashMap() {
    }

    /**
     * 建立一個新的空map,其初始表大小可容納指定數量的元素,而不需要動态調整大小。
     * Creates a new, empty map with an initial table size
     * accommodating the specified number of elements without the need
     * to dynamically resize.
     *
     * @param initialCapacity The implementation performs internal
     * sizing to accommodate this many elements.
     * @throws IllegalArgumentException if the initial capacity of
     * elements is negative
     */
    // initialCapacity 是 table 可容納的元素個數,而不是 table 的 size
    public ConcurrentHashMap(int initialCapacity) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException();
        // 若initialCapacity 大于等于MAXIMUM_CAPACITY的一半,直接設定為 MAXIMUM_CAPACITY,
        // 否則設定為 tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1))
        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
                   MAXIMUM_CAPACITY :
                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
        // 把 table的初始容量儲存到 sizeCtl中
        this.sizeCtl = cap;
    }

    /**
     * Creates a new map with the same mappings as the given map.
     *
     * @param m the map
     */
    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
        // DEFAULT_CAPACITY = 16
        this.sizeCtl = DEFAULT_CAPACITY;
        putAll(m);
    }

    /**
     * Creates a new, empty map with an initial table size based on
     * the given number of elements ({@code initialCapacity}) and
     * initial table density ({@code loadFactor}).
     *
     * @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
     * @throws IllegalArgumentException if the initial capacity of
     * elements is negative or the load factor is nonpositive
     *
     * @since 1.6
     */
    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
        this(initialCapacity, loadFactor, 1);
    }

    /**
     * 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
     */
    // initialCapacity 和 HashMap的 initialCapacity 不同。這裡的initialCapacity表示能容納的元素而不擴容
    public ConcurrentHashMap(int initialCapacity,
                             float loadFactor, int concurrencyLevel) {
        // 參數不能小于 0
        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

        // 計算table 的最小長度, +1 使table容納 initialCapacity 個元素而不會擴容
        // loadFactor 隻會影響初始化時 table的初始容量
        long size = (long)(1.0 + (long)initialCapacity / loadFactor);

        // 把size 轉成小于MAXIMUM_CAPACITY的 2 的幂
        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
            MAXIMUM_CAPACITY : tableSizeFor((int)size);
        // 把 table的長度儲存到 sizeCtl中
        this.sizeCtl = cap;
    }

    // Original (since JDK1.2) Map methods

    /**
     * {@inheritDoc}
     */
    public int size() {
        long n = sumCount();
        // 若 size 大于 Integer.MAX_VALUE, 則傳回 Integer.MAX_VALUE
        return ((n < 0L) ? 0 :
                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
                (int)n);
    }

    /**
     * {@inheritDoc}
     */
    // 判斷集合是否有元素
    public boolean isEmpty() {
        // 插入一個元素後,還沒有完成元素個數+1,然後瞬間就被另一個線程删除了,這種情況下就會
        // 出現瞬間元素個數是負的
        return sumCount() <= 0L; // ignore transient negative values    忽略瞬時負值
    }

    /**
     * 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;
        // 計算key的hash值,并将最高位置為0 (正數)
        int h = spread(key.hashCode());

        // 判斷table 不為空,且 key對應的索引位置元素不為null
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (e = tabAt(tab, (n - 1) & h)) != null) {

            // 首先判斷和第一個節點是否相等
            if ((eh = e.hash) == h) {
                // hash值相等,判斷 key是否相等
                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                    return e.val;
            }

            // eh = e.hash, 小于0 說明該節點是TreeBin 或者ForwardingNode 節點,調用的相應子類的find()方法
            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))))
                    // 找到,傳回 key 映射的值
                    return e.val;
            }
        }
        // 沒找到傳回null. ConcurrentHashMap 的 key 和 value 都不能為null, 是以傳回null
        // 說明key 不存在
        return null;
    }

    /**
     * 檢查key是否存在
     * Tests if the specified object is a key in this table.
     *
     * @param  key possible key
     *             當且僅當 key存在時傳回true,由equals()方法确定, 否則傳回false
     * @return {@code true} if and only if the specified object
     *         is a key in this table, as determined by the
     *         {@code equals} method; {@code false} otherwise
     * @throws NullPointerException if the specified key is null
     */
    public boolean containsKey(Object key) {
        // 調用get()方法,如果傳回的值不為null,說明存在
        // (因為key 和 value 都不允許為null。 HashMap調用的是getNode()方法)
        return get(key) != null;
    }

    /**
     * 如果有一個或者多個key 映射是指定的值,那麼傳回true。這個方法需要周遊整個
     * map,并且比 containsKey() 方法慢得多
     * Returns {@code true} if this map maps one or more keys to the
     * specified value. Note: This method may require a full traversal
     * of the map, and is much slower than method {@code containsKey}.
     *
     *              測試在這個map中存在的值
     * @param value value whose presence in this map is to be tested
     * @return {@code true} if this map maps one or more keys to the
     *         specified value
     * @throws NullPointerException if the specified value is null
     */
    public boolean containsValue(Object value) {
        if (value == null)
            throw new NullPointerException();
        Node<K,V>[] t;
        if ((t = table) != null) {
            // 建立了一個 Traverser
            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)))
                    // 找到,傳回true,不再繼續周遊
                    return true;
            }
        }
        // 沒有找到,傳回false
        return false;
    }

    /**
     * Maps the specified key to the specified value in this table.
     * key 和 value 都不能為 null
     * Neither the key nor the value can be null.
     *
     * value 可以用相同的key 通過 get()方法來擷取
     * <p>The value can be retrieved by calling the {@code get} method
     * with a key that is equal to the original key.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     *              傳回key映射的上一個值,null表示key是第一次放入 table中
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}
     *                          key / value 為 null 将抛出 NullPointerException
     * @throws NullPointerException if the specified key or value is null
     */
    public V put(K key, V value) {
        return putVal(key, value, false);
    }

    // onlyIfAbsent -> 是否key 不存在才進行插入
    /** 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();

        // 分散 key 的哈希值, 并将最高位置為0 (保證 hash值都為正數)
        int hash = spread(key.hashCode());

        // binCount的計數個數不包含新插入的元素
        int binCount = 0;
        for (Node<K,V>[] tab = table;;) {
            // f -> first 的意思, key對應索引位置i上的第一個節點
            // n -> table 的長度, i - > key 對應的索引位置 index,  fh -> f節點的哈希值
            Node<K,V> f; int n, i, fh;

            // 若 table為null, 或者長度為0,則初始化 table
            if (tab == null || (n = tab.length) == 0)
                // 初始化 table
                tab = initTable();

            // (n - 1) & hash 計算 key 的索引位置
            // 使用unsafe擷取索引位置i的元素值(具有volatile讀取語義)
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
                // 使用CAS設定索引i位置的值 (CAS操作具有和 volatile相同讀寫記憶體語義)
                if (casTabAt(tab, i, null,
                             new Node<K,V>(hash, key, value, null)))
                    // CAS設定成功,結束循環
                    break;                   // no lock when adding to empty bin
            }
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;

                // 使用鎖而不能使用CAS的原因是: 1、比如該索引位置有:A -> B -> C 三個節點,
                // 此時C.next = null,如果線程A要添加節點D,而線程B要删除節點C,如果線程B
                // 線上程A之前把節點C删除了,而線程A又使用CAS把線程D添加到節點C的後面,那麼
                // 将導緻節點D也被删除了;2、沒辦法控制插入和删除的并發問題

                // 需要先拿到相應索引位置上第一個元素的鎖
                synchronized (f) {
                    // 使用清單的第一個節點作為鎖本身是不夠的:當一個節點被鎖定時,任何更新必須
                    // 首先确認它仍然是鎖定後的第一個節點,如果不是,則重試。
                    if (tabAt(tab, i) == f) {
                        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)))) {
                                    // key 已存在
                                    oldVal = e.val;
                                    if (!onlyIfAbsent)
                                        // onlyIfAbsent = false 則使用新的值替換原來的值
                                        e.val = value;
                                    // binCount的元素計數個數不包含新插入的元素
                                    break;  // break 跳出循環,binCount不會再增加
                                }
                                Node<K,V> pred = e;
                                if ((e = e.next) == null) {
                                    // 因為進入這裡需要先拿到第一個元素的鎖,是以不需要使用CAS進行操作
                                    pred.next = new Node<K,V>(hash, key,
                                                              value, null);
                                    break;
                                }
                            }
                        }

                        // 添加到紅黑樹中
                        else if (f instanceof TreeBin) {
                            Node<K,V> p;
                            // binCount 設定為2,當存在競争的時候可以進行擴容,當存在多線程競争的時候 binCount <= 1,不會
                            // 進行擴容
                            binCount = 2;

                            // 如果 p != null,表示 key 映射的節點已經存在
                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                           value)) != null) {
                                oldVal = p.val;
                                if (!onlyIfAbsent)
                                    p.val = value;
                            }
                        }
                    }
                }
                if (binCount != 0) {
                    // TREEIFY_THRESHOLD = 8。 binCount不包含新插入的元素,是以加上新插入的元素,slot中元素個數達到
                    // 9個才會轉成紅黑樹,跟HashMap的 put()方法一樣,也是9個元素才會轉成紅黑樹
                    if (binCount >= TREEIFY_THRESHOLD)
                        // 把連結清單轉成紅黑樹,注意:此時已經釋放了鎖
                        treeifyBin(tab, i);

                    if (oldVal != null)
                        // oldVal != null,說明隻是使用了新的值替換原來的值,map中元素的個數不變,直接傳回原來的值
                        return oldVal;
                    break;
                }
            }
        }
        // ---------          for 循環結束        -------------

        // binCount -> 同一個索引位置的元素個數,binCount的元素計數個數不包含新插入的元素
        addCount(1L, binCount);
        return null;
    }

    /**
     * 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);
    }

    /**
     * 從map中删除key(以及它映射的值)
     * Removes the key (and its corresponding value) from this map.
     * 如果key不存在map中,則這個方法不會做任何操作
     * This method does nothing if the key is not in the map.
     *
     * @param  key the key that needs to be removed
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}
     * @throws NullPointerException if the specified key is null
     */
    public V remove(Object key) {
        return replaceNode(key, null, null);
    }

    /**
     * 實作4個公共删除/替換方法:用v替換節點值,條件是比對cv(如果非null)。
     * 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.
     */
    // cv -> compareValue ,  cv != null時,隻有key(若key存在)映射的值和cv相等
    // 才會執行元素删除,或者替換元素的值。 删除、替換的判斷依據是 value是否為null,
    // value = null,删除元素,否則替換元素的值
    // 傳回替換、或者删除元素的值。如果沒有替換/删除,那麼就算key存在也是傳回null
    final V replaceNode(Object key, V value, Object cv) {
        // 計算 key 的hash值
        int hash = spread(key.hashCode());

        for (Node<K,V>[] tab = table;;) {
            // n -> tab.length ; i -> key 對應的索引位置; fh -> f的hash值
            Node<K,V> f; int n, i, fh;

            // table為空 或者 對應的索引位置上沒有元素
            if (tab == null || (n = tab.length) == 0 ||
                (f = tabAt(tab, i = (n - 1) & hash)) == null)
                // 結束循環,傳回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) {

                        // fh >= 0 說明是該索引位置的節點連結清單結構
                        if (fh >= 0) {
                            validated = true;

                            // pred 表示周遊的上一個節點
                            for (Node<K,V> e = f, pred = null;;) {
                                K ek;
                                if (e.hash == hash &&
                                    ((ek = e.key) == key ||
                                     (ek != null && key.equals(ek)))) {
                                    // 找到key所在的節點

                                    // 把元素的值指派給 ev
                                    V ev = e.val;

                                    // cv -> compareValue ,  cv != null時,隻有key(若key存在)映射的值和cv相等
                                    // 才會執行元素删除,或者替換元素的值。 删除、替換的判斷依據是 value是否為null,

                                    // cv = null 或者 cv 和 ev相等 (如果cv != null,那麼 cv 和 ev相等才會删除元素
                                    // 或者替換元素的值)
                                    if (cv == null || cv == ev ||
                                        (ev != null && cv.equals(ev))) {

                                        // 把ev 指派給 oldValue, 如果 cv != null,且 cv和cv不相等,
                                        // 那麼就算key 存在也是傳回null
                                        oldVal = ev;
                                        if (value != null)
                                            // 如果 value != null,則元素的值替換為 value
                                            e.val = value;

                                        // 注意:删除節點時不能修改删除節點的資訊,因為有可能其他線程正在周遊該節點
                                        else if (pred != null) {
                                            // value = null, pred != null,則pred的下一個元素指向
                                            // e的下一個元素,即把 e 删除掉
                                            pred.next = e.next;
                                        }
                                        else
                                            // value = null 且 pred = null,說明删除的節點是第一個節點,把該索引位置
                                            // 的第一個元素設定為e.next,即把 e 删除掉 (e.next可能為null)
                                            setTabAt(tab, i, e.next);
                                    }

                                    // 結束内循環,此時 validated = true,是以外循環也會結束
                                    break;
                                }


                                // 節點e不是key所在的節點, pred = e
                                pred = e;

                                // 該索引位置上沒有下一個元素了,結束循環,傳回null
                                if ((e = e.next) == null)
                                    // 結束内循環,此時 validated = true,是以外循環也會結束
                                    break;
                            }
                            //    -----   内層 for 循環結束
                        }

                        // 前面已經拿到了第一個元素的鎖 (不論是連結清單還是樹結構,隻要是更新操作都需要擷取到第一個元素的鎖)
                        else if (f instanceof TreeBin) {
                            validated = true;
                            TreeBin<K,V> t = (TreeBin<K,V>)f;
                            TreeNode<K,V> r, p;
                            // r = t.root 擷取根節點
                            if ((r = t.root) != null &&
                                    // 從紅黑中查找,如果存在傳回相應的節點,否則傳回null
                                (p = r.findTreeNode(hash, key, null)) != null) {

                                V pv = p.val;
                                // cv = null 或者 cv 和 ev相等 (如果cv != null,那麼 cv 和 ev相等才會删除元素
                                // 或者替換元素的值)
                                if (cv == null || cv == pv ||
                                    (pv != null && cv.equals(pv))) {

                                    // 把ev 指派給 oldValue, 如果 cv != null,且 cv和cv不相等,
                                    // 那麼就算key 存在也是傳回null
                                    oldVal = pv;

                                    if (value != null)
                                        // value != null,替換元素的值
                                        p.val = value;
                                    // 删除p 節點,傳回true表示樹結構太小,需要轉成連結清單
                                    else if (t.removeTreeNode(p))
                                        setTabAt(tab, i, untreeify(t.first));
                                }
                            }
                        }
                    }
                }

                // validated = false的情況:擷取到鎖後第一個元素不是原來那個元素了,或者第一個節點的hash值小于0且不是 TreeBin節點
                // validated = false 說明需要繼續循環, validated = true,則判斷元素個數個數應該 -1,然後
                // 傳回原來的值,傳回null (key不存在傳回 null)
                if (validated) {
                    // key 存在,且 cv = null 或者 cv 和 key 映射的值相等時 oldVal才會不為 null
                    if (oldVal != null) {
                        if (value == null)
                            // oldVal != null, value = null,說明 key所在的節點已經被删除,
                            // 元素個數減1, check傳入 -1,表示不用進行是否擴容的判斷
                            addCount(-1L, -1);

                        // oldVal != null,則傳回 oldVal
                        return oldVal;
                    }
                    // oldVal = null,則結束循環,傳回 null
                    break;
                }
            }
        }
        return null;
    }

    /**
     * Removes all of the mappings from this map.
     */
    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;

            // 索引i前面的元素都已經删除掉了,索引i後面的元素正常情況下都已經搬移都新的table了,因為搬移
            // 是從後往前搬移的,但是多線程同時執行helpTransfer()時可能還有個别索引位置的元素還沒有完成搬移
            else if ((fh = f.hash) == MOVED) {
                // 目前正在進行擴容,幫忙轉移元素, helpTransfer()會傳回新的table
                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) {
                            // 隻要計算該索引位置上有幾個元素就可以了,把該索引位置的元素設定為null
                            // 進行一次性删除
                            --delta;
                            p = p.next;
                        }
                        // 設定該索引位置上的元素為null,然後 i++
                        setTabAt(tab, i++, null);
                    }
                }
            }
        }

        // 更新元素個數
        if (delta != 0L)
            addCount(delta, -1);
    }

    /**
     * 傳回這個map中包含的keys的一個set集合
     * Returns a {@link Set} view of the keys contained in this map.
     * 集合由map支援,是以對map的更改将反映在集合中,反之亦然。
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa. The set supports element
     * 這個set集合支援元素移除,即從這個map中移除對應的映射,
     * removal, which removes the corresponding mapping from this map,
     * via the {@code Iterator.remove}, {@code Set.remove},
     * {@code removeAll}, {@code retainAll}, and {@code clear}
     *              它不支援add或addAll操作。
     * operations.  It does not support the {@code add} or
     * {@code addAll} operations.
     *
     * <p>The view's iterators and spliterators are
     * <a href="package-summary.html#Weakly" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" ><i>weakly consistent</i></a>.
     *
     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
     *
     * @return the set view
     */
    // 注意: 傳回的Set不支援add或addAll操作。
    public KeySetView<K,V> keySet() {
        KeySetView<K,V> ks;
        // value 傳入null,是以不支援增加元素
        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
    }

    /**
     * 傳回這個map中的values的一個集合視圖。
     * Returns a {@link Collection} view of the values contained in this map.
     * 這個集合由這個map支援,是以對這個map的修改會反映到這個集合中,反之亦然。
     * The collection is backed by the map, so changes to the map are
     * reflected in the collection, and vice-versa.  The collection
     * 這個集合支援元素移除,即從map中移除相應的映射。
     * supports element removal, which removes the corresponding
     * mapping from this map, via the {@code Iterator.remove},
     * {@code Collection.remove}, {@code removeAll},
     * {@code retainAll}, and {@code clear} operations.  It does not
     * 它不支援add或addAll操作。
     * support the {@code add} or {@code addAll} operations.
     *
     * <p>The view's iterators and spliterators are
     * <a href="package-summary.html#Weakly" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" ><i>weakly consistent</i></a>.
     *
     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}
     * and {@link Spliterator#NONNULL}.
     *
     * @return the collection view
     */
    public Collection<V> values() {
        ValuesView<K,V> vs;
        // 建立ValuesView
        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
    }

    /**
     * Returns a {@link Set} view of the mappings contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  The set supports element
     * removal, which removes the corresponding mapping from the map,
     * via the {@code Iterator.remove}, {@code Set.remove},
     * {@code removeAll}, {@code retainAll}, and {@code clear}
     * operations.
     *
     * <p>The view's iterators and spliterators are
     * <a href="package-summary.html#Weakly" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" ><i>weakly consistent</i></a>.
     *
     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
     *
     * @return the set view
     */
    public Set<Map.Entry<K,V>> entrySet() {
        EntrySetView<K,V> es;
        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
    }

    /**
     * Returns the hash code value for this {@link Map}, i.e.,
     * the sum of, for each key-value pair in the map,
     * {@code key.hashCode() ^ value.hashCode()}.
     *
     * @return the hash code value for this map
     */
    public int hashCode() {
        int h = 0;
        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; )
                h += p.key.hashCode() ^ p.val.hashCode();
        }
        return h;
    }

    /**
     * Returns a string representation of this map.  The string
     * representation consists of a list of key-value mappings (in no
     * particular order) enclosed in braces ("{@code {}}").  Adjacent
     * mappings are separated by the characters {@code ", "} (comma
     * and space).  Each key-value mapping is rendered as the key
     * followed by an equals sign ("{@code =}") followed by the
     * associated value.
     *
     * @return a string representation of this map
     */
    public String toString() {
        Node<K,V>[] t;
        int f = (t = table) == null ? 0 : t.length;
        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
        StringBuilder sb = new StringBuilder();
        sb.append('{');
        Node<K,V> p;
        if ((p = it.advance()) != null) {
            for (;;) {
                K k = p.key;
                V v = p.val;
                sb.append(k == this ? "(this Map)" : k);
                sb.append('=');
                sb.append(v == this ? "(this Map)" : v);
                if ((p = it.advance()) == null)
                    break;
                sb.append(',').append(' ');
            }
        }
        return sb.append('}').toString();
    }

    /**
     * Compares the specified object with this map for equality.
     * Returns {@code true} if the given object is a map with the same
     * mappings as this map.  This operation may return misleading
     * results if either map is concurrently modified during execution
     * of this method.
     *
     * @param o object to be compared for equality with this map
     * @return {@code true} if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o != this) {
            if (!(o instanceof Map))
                return false;
            Map<?,?> m = (Map<?,?>) o;
            Node<K,V>[] t;
            int f = (t = table) == null ? 0 : t.length;
            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
            for (Node<K,V> p; (p = it.advance()) != null; ) {
                V val = p.val;
                Object v = m.get(p.key);
                if (v == null || (v != val && !v.equals(val)))
                    return false;
            }
            for (Map.Entry<?,?> e : m.entrySet()) {
                Object mk, mv, v;
                if ((mk = e.getKey()) == null ||
                    (mv = e.getValue()) == null ||
                    (v = get(mk)) == null ||
                    (mv != v && !mv.equals(v)))
                    return false;
            }
        }
        return true;
    }

    /**
     * Stripped-down version of helper class used in previous version,
     * declared for the sake of serialization compatibility
     */
    static class Segment<K,V> extends ReentrantLock implements Serializable {
        private static final long serialVersionUID = 2249069246763182397L;
        final float loadFactor;
        Segment(float lf) { this.loadFactor = lf; }
    }

    /**
     * Saves the state of the {@code ConcurrentHashMap} instance to a
     * stream (i.e., serializes it).
     * @param s the stream
     * @throws java.io.IOException if an I/O error occurs
     * @serialData
     * the key (Object) and value (Object)
     * for each key-value mapping, followed by a null pair.
     * The key-value mappings are emitted in no particular order.
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // For serialization compatibility
        // Emulate segment calculation from previous version of this class
        int sshift = 0;
        int ssize = 1;
        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
            ++sshift;
            ssize <<= 1;
        }
        int segmentShift = 32 - sshift;
        int segmentMask = ssize - 1;
        @SuppressWarnings("unchecked")
        Segment<K,V>[] segments = (Segment<K,V>[])
            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
        for (int i = 0; i < segments.length; ++i)
            segments[i] = new Segment<K,V>(LOAD_FACTOR);
        s.putFields().put("segments", segments);
        s.putFields().put("segmentShift", segmentShift);
        s.putFields().put("segmentMask", segmentMask);
        s.writeFields();

        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; ) {
                s.writeObject(p.key);
                s.writeObject(p.val);
            }
        }
        s.writeObject(null);
        s.writeObject(null);
        segments = null; // throw away
    }

    /**
     * Reconstitutes the instance from a stream (that is, deserializes it).
     * @param s the stream
     * @throws ClassNotFoundException if the class of a serialized object
     *         could not be found
     * @throws java.io.IOException if an I/O error occurs
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        /*
         * To improve performance in typical cases, we create nodes
         * while reading, then place in table once size is known.
         * However, we must also validate uniqueness and deal with
         * overpopulated bins while doing so, which requires
         * specialized versions of putVal mechanics.
         */
        sizeCtl = -1; // force exclusion for table construction
        s.defaultReadObject();
        long size = 0L;
        Node<K,V> p = null;
        for (;;) {
            @SuppressWarnings("unchecked")
            K k = (K) s.readObject();
            @SuppressWarnings("unchecked")
            V v = (V) s.readObject();
            if (k != null && v != null) {
                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
                ++size;
            }
            else
                break;
        }
        if (size == 0L)
            sizeCtl = 0;
        else {
            int n;
            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
                n = MAXIMUM_CAPACITY;
            else {
                int sz = (int)size;
                n = tableSizeFor(sz + (sz >>> 1) + 1);
            }
            @SuppressWarnings("unchecked")
            Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
            int mask = n - 1;
            long added = 0L;
            while (p != null) {
                boolean insertAtFront;
                Node<K,V> next = p.next, first;
                int h = p.hash, j = h & mask;
                if ((first = tabAt(tab, j)) == null)
                    insertAtFront = true;
                else {
                    K k = p.key;
                    if (first.hash < 0) {
                        TreeBin<K,V> t = (TreeBin<K,V>)first;
                        if (t.putTreeVal(h, k, p.val) == null)
                            ++added;
                        insertAtFront = false;
                    }
                    else {
                        int binCount = 0;
                        insertAtFront = true;
                        Node<K,V> q; K qk;
                        for (q = first; q != null; q = q.next) {
                            if (q.hash == h &&
                                ((qk = q.key) == k ||
                                 (qk != null && k.equals(qk)))) {
                                insertAtFront = false;
                                break;
                            }
                            ++binCount;
                        }
                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
                            insertAtFront = false;
                            ++added;
                            p.next = first;
                            TreeNode<K,V> hd = null, tl = null;
                            for (q = p; q != null; q = q.next) {
                                TreeNode<K,V> t = new TreeNode<K,V>
                                    (q.hash, q.key, q.val, null, null);
                                if ((t.prev = tl) == null)
                                    hd = t;
                                else
                                    tl.next = t;
                                tl = t;
                            }
                            setTabAt(tab, j, new TreeBin<K,V>(hd));
                        }
                    }
                }
                if (insertAtFront) {
                    ++added;
                    p.next = first;
                    setTabAt(tab, j, p);
                }
                p = next;
            }
            table = tab;
            sizeCtl = n - (n >>> 2);
            baseCount = added;
        }
    }

    // ConcurrentMap methods

    /**
     * {@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 putIfAbsent(K key, V value) {
        return putVal(key, value, true);
    }

    /**
     * {@inheritDoc}
     *
     * @throws NullPointerException if the specified key is null
     */
    public boolean remove(Object key, Object value) {
        if (key == null)
            throw new NullPointerException();
        return value != null && replaceNode(key, null, value) != null;
    }

    /**
     * {@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;
    }

    /**
     * {@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);
    }

    // Overrides of JDK8+ Map extension method defaults

    /**
     * Returns the value to which the specified key is mapped, or the
     * given default value if this map contains no mapping for the
     * key.
     *
     * @param key the key whose associated value is to be returned
     * @param defaultValue the value to return if this map contains
     * no mapping for the given key
     * @return the mapping for the key, if present; else the default value
     * @throws NullPointerException if the specified key is null
     */
    public V getOrDefault(Object key, V defaultValue) {
        V v;
        return (v = get(key)) == null ? defaultValue : v;
    }

    public void forEach(BiConsumer<? super K, ? super V> action) {
        if (action == 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; ) {
                action.accept(p.key, p.val);
            }
        }
    }

    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
        if (function == 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 oldValue = p.val;
                for (K key = p.key;;) {
                    V newValue = function.apply(key, oldValue);
                    if (newValue == null)
                        throw new NullPointerException();
                    if (replaceNode(key, newValue, oldValue) != null ||
                        (oldValue = get(key)) == null)
                        break;
                }
            }
        }
    }