Class ConcurrentHashMapV8<K,​V>

  • Type Parameters:
    K - the type of keys maintained by this map
    V - the type of mapped values
    All Implemented Interfaces:
    java.io.Serializable, java.util.concurrent.ConcurrentMap<K,​V>, java.util.Map<K,​V>

    class ConcurrentHashMapV8<K,​V>
    extends java.util.AbstractMap<K,​V>
    implements java.util.concurrent.ConcurrentMap<K,​V>, java.io.Serializable
    A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.

    Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. (More formally, an update operation for a given key bears a happens-before relation with any (non-null) retrieval for that key reporting the updated value.) For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries. Similarly, Iterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time. Bear in mind that the results of aggregate status methods including size, isEmpty, and containsValue are typically useful only when a map is not undergoing concurrent updates in other threads. Otherwise the results of these methods reflect transient states that may be adequate for monitoring or estimation purposes, but not for program control.

    The table is dynamically expanded when there are too many collisions (i.e., keys that have distinct hash codes but fall into the same slot modulo the table size), with the expected average effect of maintaining roughly two bins per mapping (corresponding to a 0.75 load factor threshold for resizing). There may be much variance around this average as mappings are added and removed, but overall, this maintains a commonly accepted time/space tradeoff for hash tables. However, resizing this or any other kind of hash table may be a relatively slow operation. When possible, it is a good idea to provide a size estimate as an optional initialCapacity constructor argument. An additional optional loadFactor constructor argument provides a further means of customizing initial table capacity by specifying the table density to be used in calculating the amount of space to allocate for the given number of elements. Also, for compatibility with previous versions of this class, constructors may optionally specify an expected concurrencyLevel as an additional hint for internal sizing. Note that using many keys with exactly the same hashCode() is a sure way to slow down performance of any hash table. To ameliorate impact, when keys are Comparable, this class may use comparison order among keys to help break ties.

    A Set projection of a ConcurrentHashMapV8 may be created (using newKeySet() or newKeySet(int)), or viewed (using keySet(Object) when only keys are of interest, and the mapped values are (perhaps transiently) not used or all take the same mapping value.

    This class and its views and iterators implement all of the optional methods of the Map and Iterator interfaces.

    Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.

    ConcurrentHashMapV8s support a set of sequential and parallel bulk operations that are designed to be safely, and often sensibly, applied even with maps that are being concurrently updated by other threads; for example, when computing a snapshot summary of the values in a shared registry. There are three kinds of operation, each with four forms, accepting functions with Keys, Values, Entries, and (Key, Value) arguments and/or return values. Because the elements of a ConcurrentHashMapV8 are not ordered in any particular way, and may be processed in different orders in different parallel executions, the correctness of supplied functions should not depend on any ordering, or on any other objects or values that may transiently change while computation is in progress; and except for forEach actions, should ideally be side-effect-free. Bulk operations on Map.Entry objects do not support method setValue.

    • forEach: Perform a given action on each element. A variant form applies a given transformation on each element before performing the action.
    • search: Return the first available non-null result of applying a given function on each element; skipping further search when a result is found.
    • reduce: Accumulate each element. The supplied reduction function cannot rely on ordering (more formally, it should be both associative and commutative). There are five variants:
      • Plain reductions. (There is not a form of this method for (key, value) function arguments since there is no corresponding return type.)
      • Mapped reductions that accumulate the results of a given function applied to each element.
      • Reductions to scalar doubles, longs, and ints, using a given basis value.

    These bulk operations accept a parallelismThreshold argument. Methods proceed sequentially if the current map size is estimated to be less than the given threshold. Using a value of Long.MAX_VALUE suppresses all parallelism. Using a value of 1 results in maximal parallelism by partitioning into enough subtasks to fully utilize the ForkJoinPool#commonPool() that is used for all parallel computations. Normally, you would initially choose one of these extreme values, and then measure performance of using in-between values that trade off overhead versus throughput.

    The concurrency properties of bulk operations follow from those of ConcurrentHashMapV8: Any non-null result returned from get(key) and related access methods bears a happens-before relation with the associated insertion or update. The result of any bulk operation reflects the composition of these per-element relations (but is not necessarily atomic with respect to the map as a whole unless it is somehow known to be quiescent). Conversely, because keys and values in the map are never null, null serves as a reliable atomic indicator of the current lack of any result. To maintain this property, null serves as an implicit basis for all non-scalar reduction operations. For the double, long, and int versions, the basis should be one that, when combined with any other value, returns that other value (more formally, it should be the identity element for the reduction). Most common reductions have these properties; for example, computing a sum with basis 0 or a minimum with basis MAX_VALUE.

    Search and transformation functions provided as arguments should similarly return null to indicate the lack of any result (in which case it is not used). In the case of mapped reductions, this also enables transformations to serve as filters, returning null (or, in the case of primitive specializations, the identity basis) if the element should not be combined. You can create compound transformations and filterings by composing them yourself under this "null means there is nothing there now" rule before using them in search or reduce operations.

    Methods accepting and/or returning Entry arguments maintain key-value associations. They may be useful for example when finding the key for the greatest value. Note that "plain" Entry arguments can be supplied using new AbstractMap.SimpleEntry(k,v).

    Bulk operations may complete abruptly, throwing an exception encountered in the application of a supplied function. Bear in mind when handling such exceptions that other concurrently executing functions could also have thrown exceptions, or would have done so if the first exception had not occurred.

    Speedups for parallel compared to sequential forms are common but not guaranteed. Parallel operations involving brief functions on small maps may execute more slowly than sequential forms if the underlying work to parallelize the computation is more expensive than the computation itself. Similarly, parallelization may not lead to much actual parallelism if all processors are busy performing unrelated tasks.

    All arguments to all task methods must be non-null.

    jsr166e note: During transition, this class uses nested functional interfaces with different names but the same forms as those expected for JDK8.

    This class is a member of the Java Collections Framework.

    • Constructor Summary

      Constructors 
      Constructor Description
      ConcurrentHashMapV8()
      Creates a new, empty map with the default initial table size (16).
      ConcurrentHashMapV8​(int initialCapacity)
      Creates a new, empty map with an initial table size accommodating the specified number of elements without the need to dynamically resize.
      ConcurrentHashMapV8​(int initialCapacity, float loadFactor)
      Creates a new, empty map with an initial table size based on the given number of elements (initialCapacity) and initial table density (loadFactor).
      ConcurrentHashMapV8​(int initialCapacity, float loadFactor, int concurrencyLevel)
      Creates a new, empty map with an initial table size based on the given number of elements (initialCapacity), table density (loadFactor), and number of concurrently updating threads (concurrencyLevel).
      ConcurrentHashMapV8​(java.util.Map<? extends K,​? extends V> m)
      Creates a new map with the same mappings as the given map.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      private void addCount​(long x, int check)
      Adds to count, and if table is too small and not already resizing, initiates transfer.
      (package private) static <K,​V>
      boolean
      casTabAt​(ConcurrentHashMapV8.Node<K,​V>[] tab, int i, ConcurrentHashMapV8.Node<K,​V> c, ConcurrentHashMapV8.Node<K,​V> v)  
      void clear()
      Removes all of the mappings from this map.
      (package private) static java.lang.Class<?> comparableClassFor​(java.lang.Object x)
      Returns x's Class if it is of the form "class C implements Comparable", else null.
      (package private) static int compareComparables​(java.lang.Class<?> kc, java.lang.Object k, java.lang.Object x)
      Returns k.compareTo(x) if x matches kc (k's screened comparable class), else 0.
      boolean contains​(java.lang.Object value)
      Deprecated.
      boolean containsKey​(java.lang.Object key)
      Tests if the specified object is a key in this table.
      boolean containsValue​(java.lang.Object value)
      Returns true if this map maps one or more keys to the specified value.
      java.util.Enumeration<V> elements()
      Returns an enumeration of the values in this table.
      java.util.Set<java.util.Map.Entry<K,​V>> entrySet()
      Returns a Set view of the mappings contained in this map.
      boolean equals​(java.lang.Object o)
      Compares the specified object with this map for equality.
      private void fullAddCount​(long x, ConcurrentHashMapV8.CounterHashCode hc, boolean wasUncontended)  
      V get​(java.lang.Object key)
      Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
      V getOrDefault​(java.lang.Object key, V defaultValue)
      Returns the value to which the specified key is mapped, or the given default value if this map contains no mapping for the key.
      private static sun.misc.Unsafe getUnsafe()
      Returns a sun.misc.Unsafe.
      int hashCode()
      Returns the hash code value for this Map, i.e., the sum of, for each key-value pair in the map, key.hashCode() ^ value.hashCode().
      (package private) ConcurrentHashMapV8.Node<K,​V>[] helpTransfer​(ConcurrentHashMapV8.Node<K,​V>[] tab, ConcurrentHashMapV8.Node<K,​V> f)
      Helps transfer if a resize is in progress.
      private ConcurrentHashMapV8.Node<K,​V>[] initTable()
      Initializes table, using the size recorded in sizeCtl.
      boolean isEmpty()
      java.util.Enumeration<K> keys()
      Returns an enumeration of the keys in this table.
      ConcurrentHashMapV8.KeySetView<K,​V> keySet()
      Returns a Set view of the keys contained in this map.
      ConcurrentHashMapV8.KeySetView<K,​V> keySet​(V mappedValue)
      Returns a Set view of the keys in this map, using the given common mapped value for any additions (i.e., Collection.add(E) and Collection.addAll(Collection)).
      long mappingCount()
      Returns the number of mappings.
      static <K> ConcurrentHashMapV8.KeySetView<K,​java.lang.Boolean> newKeySet()
      Creates a new Set backed by a ConcurrentHashMapV8 from the given type to Boolean.TRUE.
      static <K> ConcurrentHashMapV8.KeySetView<K,​java.lang.Boolean> newKeySet​(int initialCapacity)
      Creates a new Set backed by a ConcurrentHashMapV8 from the given type to Boolean.TRUE.
      V put​(K key, V value)
      Maps the specified key to the specified value in this table.
      void putAll​(java.util.Map<? extends K,​? extends V> m)
      Copies all of the mappings from the specified map to this one.
      V putIfAbsent​(K key, V value)
      (package private) V putVal​(K key, V value, boolean onlyIfAbsent)
      Implementation for put and putIfAbsent
      private void readObject​(java.io.ObjectInputStream s)
      Reconstitutes the instance from a stream (that is, deserializes it).
      V remove​(java.lang.Object key)
      Removes the key (and its corresponding value) from this map.
      boolean remove​(java.lang.Object key, java.lang.Object value)
      V replace​(K key, V value)
      boolean replace​(K key, V oldValue, V newValue)
      (package private) V replaceNode​(java.lang.Object key, V value, java.lang.Object cv)
      Implementation for the four public remove/replace methods: Replaces node value with v, conditional upon match of cv if non-null.
      (package private) static <K,​V>
      void
      setTabAt​(ConcurrentHashMapV8.Node<K,​V>[] tab, int i, ConcurrentHashMapV8.Node<K,​V> v)  
      int size()
      (package private) static int spread​(int h)
      Spreads (XORs) higher bits of hash to lower and also forces top bit to 0.
      (package private) long sumCount()  
      (package private) static <K,​V>
      ConcurrentHashMapV8.Node<K,​V>
      tabAt​(ConcurrentHashMapV8.Node<K,​V>[] tab, int i)  
      private static int tableSizeFor​(int c)
      Returns a power of two table size for the given desired capacity.
      java.lang.String toString()
      Returns a string representation of this map.
      private void transfer​(ConcurrentHashMapV8.Node<K,​V>[] tab, ConcurrentHashMapV8.Node<K,​V>[] nextTab)
      Moves and/or copies the nodes in each bin to new table.
      private void treeifyBin​(ConcurrentHashMapV8.Node<K,​V>[] tab, int index)
      Replaces all linked nodes in bin at given index unless table is too small, in which case resizes instead.
      private void tryPresize​(int size)
      Tries to presize table to accommodate the given number of elements.
      (package private) static <K,​V>
      ConcurrentHashMapV8.Node<K,​V>
      untreeify​(ConcurrentHashMapV8.Node<K,​V> b)
      Returns a list on non-TreeNodes replacing those in given list.
      java.util.Collection<V> values()
      Returns a Collection view of the values contained in this map.
      private void writeObject​(java.io.ObjectOutputStream s)
      Saves the state of the ConcurrentHashMapV8 instance to a stream (i.e., serializes it).
      • Methods inherited from class java.util.AbstractMap

        clone
      • Methods inherited from class java.lang.Object

        finalize, getClass, notify, notifyAll, wait, wait, wait
      • Methods inherited from interface java.util.concurrent.ConcurrentMap

        compute, computeIfAbsent, computeIfPresent, forEach, merge, replaceAll
    • Field Detail

      • MAXIMUM_CAPACITY

        private static final int MAXIMUM_CAPACITY
        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.
        See Also:
        Constant Field Values
      • DEFAULT_CAPACITY

        private static final int DEFAULT_CAPACITY
        The default initial table capacity. Must be a power of 2 (i.e., at least 1) and at most MAXIMUM_CAPACITY.
        See Also:
        Constant Field Values
      • MAX_ARRAY_SIZE

        static final int MAX_ARRAY_SIZE
        The largest possible (non-power of two) array size. Needed by toArray and related methods.
        See Also:
        Constant Field Values
      • DEFAULT_CONCURRENCY_LEVEL

        private static final int DEFAULT_CONCURRENCY_LEVEL
        The default concurrency level for this table. Unused but defined for compatibility with previous versions of this class.
        See Also:
        Constant Field Values
      • LOAD_FACTOR

        private static final float LOAD_FACTOR
        The load factor for this table. Overrides of this value in constructors affect only the initial table capacity. The actual floating point value isn't normally used -- it is simpler to use expressions such as n - (n >>> 2) for the associated resizing threshold.
        See Also:
        Constant Field Values
      • TREEIFY_THRESHOLD

        static final int TREEIFY_THRESHOLD
        The bin count threshold for using a tree rather than list for a bin. Bins are converted to trees when adding an element to a bin with at least this many nodes. 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.
        See Also:
        Constant Field Values
      • UNTREEIFY_THRESHOLD

        static final int UNTREEIFY_THRESHOLD
        The bin count threshold for untreeifying a (split) bin during a resize operation. Should be less than TREEIFY_THRESHOLD, and at most 6 to mesh with shrinkage detection under removal.
        See Also:
        Constant Field Values
      • MIN_TREEIFY_CAPACITY

        static final int MIN_TREEIFY_CAPACITY
        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.
        See Also:
        Constant Field Values
      • MIN_TRANSFER_STRIDE

        private static final int MIN_TRANSFER_STRIDE
        Minimum number of rebinnings per transfer step. Ranges are subdivided to allow multiple resizer threads. This value serves as a lower bound to avoid resizers encountering excessive memory contention. The value should be at least DEFAULT_CAPACITY.
        See Also:
        Constant Field Values
      • NCPU

        static final int NCPU
        Number of CPUS, to place bounds on some sizings
      • serialPersistentFields

        private static final java.io.ObjectStreamField[] serialPersistentFields
        For serialization compatibility.
      • table

        transient volatile ConcurrentHashMapV8.Node<K,​V>[] table
        The array of bins. Lazily initialized upon first insertion. Size is always a power of two. Accessed directly by iterators.
      • nextTable

        private transient volatile ConcurrentHashMapV8.Node<K,​V>[] nextTable
        The next table to use; non-null only while resizing.
      • baseCount

        private transient volatile long baseCount
        Base counter value, used mainly when there is no contention, but also as a fallback during table initialization races. Updated via CAS.
      • sizeCtl

        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.
      • transferIndex

        private transient volatile int transferIndex
        The next table index (plus one) to split while resizing.
      • transferOrigin

        private transient volatile int transferOrigin
        The least available table index to split while resizing.
      • cellsBusy

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

        static final java.util.concurrent.atomic.AtomicInteger counterHashCodeGenerator
        Generates initial value for per-thread CounterHashCodes.
      • SEED_INCREMENT

        static final int SEED_INCREMENT
        Increment for counterHashCodeGenerator. See class ThreadLocal for explanation.
        See Also:
        Constant Field Values
      • threadCounterHashCode

        static final java.lang.ThreadLocal<ConcurrentHashMapV8.CounterHashCode> threadCounterHashCode
        Per-thread counter hash codes. Shared across all instances.
      • U

        private static final sun.misc.Unsafe U
      • SIZECTL

        private static final long SIZECTL
      • TRANSFERINDEX

        private static final long TRANSFERINDEX
      • TRANSFERORIGIN

        private static final long TRANSFERORIGIN
      • BASECOUNT

        private static final long BASECOUNT
      • CELLSBUSY

        private static final long CELLSBUSY
      • CELLVALUE

        private static final long CELLVALUE
      • ABASE

        private static final long ABASE
      • ASHIFT

        private static final int ASHIFT
    • Constructor Detail

      • ConcurrentHashMapV8

        ConcurrentHashMapV8()
        Creates a new, empty map with the default initial table size (16).
      • ConcurrentHashMapV8

        ConcurrentHashMapV8​(int initialCapacity)
        Creates a new, empty map with an initial table size accommodating the specified number of elements without the need to dynamically resize.
        Parameters:
        initialCapacity - The implementation performs internal sizing to accommodate this many elements.
        Throws:
        java.lang.IllegalArgumentException - if the initial capacity of elements is negative
      • ConcurrentHashMapV8

        ConcurrentHashMapV8​(java.util.Map<? extends K,​? extends V> m)
        Creates a new map with the same mappings as the given map.
        Parameters:
        m - the map
      • ConcurrentHashMapV8

        ConcurrentHashMapV8​(int initialCapacity,
                            float loadFactor)
        Creates a new, empty map with an initial table size based on the given number of elements (initialCapacity) and initial table density (loadFactor).
        Parameters:
        initialCapacity - the initial capacity. The implementation performs internal sizing to accommodate this many elements, given the specified load factor.
        loadFactor - the load factor (table density) for establishing the initial table size
        Throws:
        java.lang.IllegalArgumentException - if the initial capacity of elements is negative or the load factor is nonpositive
        Since:
        1.6
      • ConcurrentHashMapV8

        ConcurrentHashMapV8​(int initialCapacity,
                            float loadFactor,
                            int concurrencyLevel)
        Creates a new, empty map with an initial table size based on the given number of elements (initialCapacity), table density (loadFactor), and number of concurrently updating threads (concurrencyLevel).
        Parameters:
        initialCapacity - the initial capacity. The implementation performs internal sizing to accommodate this many elements, given the specified load factor.
        loadFactor - the load factor (table density) for establishing the initial table size
        concurrencyLevel - the estimated number of concurrently updating threads. The implementation may use this value as a sizing hint.
        Throws:
        java.lang.IllegalArgumentException - if the initial capacity is negative or the load factor or concurrencyLevel are nonpositive
    • Method Detail

      • spread

        static final int spread​(int h)
        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.
      • tableSizeFor

        private static final int tableSizeFor​(int c)
        Returns a power of two table size for the given desired capacity. See Hackers Delight, sec 3.2
      • comparableClassFor

        static java.lang.Class<?> comparableClassFor​(java.lang.Object x)
        Returns x's Class if it is of the form "class C implements Comparable", else null.
      • compareComparables

        static int compareComparables​(java.lang.Class<?> kc,
                                      java.lang.Object k,
                                      java.lang.Object x)
        Returns k.compareTo(x) if x matches kc (k's screened comparable class), else 0.
      • size

        public int size()
        Specified by:
        size in interface java.util.Map<K,​V>
        Overrides:
        size in class java.util.AbstractMap<K,​V>
      • isEmpty

        public boolean isEmpty()
        Specified by:
        isEmpty in interface java.util.Map<K,​V>
        Overrides:
        isEmpty in class java.util.AbstractMap<K,​V>
      • get

        public V get​(java.lang.Object key)
        Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

        More formally, if this map contains a mapping from a key k to a value v such that key.equals(k), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)

        Specified by:
        get in interface java.util.Map<K,​V>
        Overrides:
        get in class java.util.AbstractMap<K,​V>
        Throws:
        java.lang.NullPointerException - if the specified key is null
      • containsKey

        public boolean containsKey​(java.lang.Object key)
        Tests if the specified object is a key in this table.
        Specified by:
        containsKey in interface java.util.Map<K,​V>
        Overrides:
        containsKey in class java.util.AbstractMap<K,​V>
        Parameters:
        key - possible key
        Returns:
        true if and only if the specified object is a key in this table, as determined by the equals method; false otherwise
        Throws:
        java.lang.NullPointerException - if the specified key is null
      • containsValue

        public boolean containsValue​(java.lang.Object value)
        Returns 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 containsKey.
        Specified by:
        containsValue in interface java.util.Map<K,​V>
        Overrides:
        containsValue in class java.util.AbstractMap<K,​V>
        Parameters:
        value - value whose presence in this map is to be tested
        Returns:
        true if this map maps one or more keys to the specified value
        Throws:
        java.lang.NullPointerException - if the specified value is null
      • put

        public V put​(K key,
                     V value)
        Maps the specified key to the specified value in this table. Neither the key nor the value can be null.

        The value can be retrieved by calling the get method with a key that is equal to the original key.

        Specified by:
        put in interface java.util.Map<K,​V>
        Overrides:
        put in class java.util.AbstractMap<K,​V>
        Parameters:
        key - key with which the specified value is to be associated
        value - value to be associated with the specified key
        Returns:
        the previous value associated with key, or null if there was no mapping for key
        Throws:
        java.lang.NullPointerException - if the specified key or value is null
      • putVal

        final V putVal​(K key,
                       V value,
                       boolean onlyIfAbsent)
        Implementation for put and putIfAbsent
      • putAll

        public void putAll​(java.util.Map<? extends K,​? extends V> 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.
        Specified by:
        putAll in interface java.util.Map<K,​V>
        Overrides:
        putAll in class java.util.AbstractMap<K,​V>
        Parameters:
        m - mappings to be stored in this map
      • remove

        public V remove​(java.lang.Object key)
        Removes the key (and its corresponding value) from this map. This method does nothing if the key is not in the map.
        Specified by:
        remove in interface java.util.Map<K,​V>
        Overrides:
        remove in class java.util.AbstractMap<K,​V>
        Parameters:
        key - the key that needs to be removed
        Returns:
        the previous value associated with key, or null if there was no mapping for key
        Throws:
        java.lang.NullPointerException - if the specified key is null
      • replaceNode

        final V replaceNode​(java.lang.Object key,
                            V value,
                            java.lang.Object cv)
        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.
      • clear

        public void clear()
        Removes all of the mappings from this map.
        Specified by:
        clear in interface java.util.Map<K,​V>
        Overrides:
        clear in class java.util.AbstractMap<K,​V>
      • keySet

        public ConcurrentHashMapV8.KeySetView<K,​V> keySet()
        Returns a Set view of the keys 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 this map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

        The view's iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

        Specified by:
        keySet in interface java.util.Map<K,​V>
        Overrides:
        keySet in class java.util.AbstractMap<K,​V>
        Returns:
        the set view
      • values

        public java.util.Collection<V> values()
        Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. The collection supports element removal, which removes the corresponding mapping from this map, via the Iterator.remove, Collection.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

        The view's iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

        Specified by:
        values in interface java.util.Map<K,​V>
        Overrides:
        values in class java.util.AbstractMap<K,​V>
        Returns:
        the collection view
      • entrySet

        public java.util.Set<java.util.Map.Entry<K,​V>> entrySet()
        Returns a 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 Iterator.remove, Set.remove, removeAll, retainAll, and clear operations.

        The view's iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

        Specified by:
        entrySet in interface java.util.Map<K,​V>
        Specified by:
        entrySet in class java.util.AbstractMap<K,​V>
        Returns:
        the set view
      • hashCode

        public int hashCode()
        Returns the hash code value for this Map, i.e., the sum of, for each key-value pair in the map, key.hashCode() ^ value.hashCode().
        Specified by:
        hashCode in interface java.util.Map<K,​V>
        Overrides:
        hashCode in class java.util.AbstractMap<K,​V>
        Returns:
        the hash code value for this map
      • toString

        public java.lang.String toString()
        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 ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value.
        Overrides:
        toString in class java.util.AbstractMap<K,​V>
        Returns:
        a string representation of this map
      • equals

        public boolean equals​(java.lang.Object o)
        Compares the specified object with this map for equality. Returns 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.
        Specified by:
        equals in interface java.util.Map<K,​V>
        Overrides:
        equals in class java.util.AbstractMap<K,​V>
        Parameters:
        o - object to be compared for equality with this map
        Returns:
        true if the specified object is equal to this map
      • writeObject

        private void writeObject​(java.io.ObjectOutputStream s)
                          throws java.io.IOException
        Saves the state of the ConcurrentHashMapV8 instance to a stream (i.e., serializes it).
        Parameters:
        s - the stream
        Throws:
        java.io.IOException - if an I/O error occurs
      • readObject

        private void readObject​(java.io.ObjectInputStream s)
                         throws java.io.IOException,
                                java.lang.ClassNotFoundException
        Reconstitutes the instance from a stream (that is, deserializes it).
        Parameters:
        s - the stream
        Throws:
        java.lang.ClassNotFoundException - if the class of a serialized object could not be found
        java.io.IOException - if an I/O error occurs
      • putIfAbsent

        public V putIfAbsent​(K key,
                             V value)
        Specified by:
        putIfAbsent in interface java.util.concurrent.ConcurrentMap<K,​V>
        Specified by:
        putIfAbsent in interface java.util.Map<K,​V>
        Returns:
        the previous value associated with the specified key, or null if there was no mapping for the key
        Throws:
        java.lang.NullPointerException - if the specified key or value is null
      • remove

        public boolean remove​(java.lang.Object key,
                              java.lang.Object value)
        Specified by:
        remove in interface java.util.concurrent.ConcurrentMap<K,​V>
        Specified by:
        remove in interface java.util.Map<K,​V>
        Throws:
        java.lang.NullPointerException - if the specified key is null
      • replace

        public boolean replace​(K key,
                               V oldValue,
                               V newValue)
        Specified by:
        replace in interface java.util.concurrent.ConcurrentMap<K,​V>
        Specified by:
        replace in interface java.util.Map<K,​V>
        Throws:
        java.lang.NullPointerException - if any of the arguments are null
      • replace

        public V replace​(K key,
                         V value)
        Specified by:
        replace in interface java.util.concurrent.ConcurrentMap<K,​V>
        Specified by:
        replace in interface java.util.Map<K,​V>
        Returns:
        the previous value associated with the specified key, or null if there was no mapping for the key
        Throws:
        java.lang.NullPointerException - if the specified key or value is null
      • getOrDefault

        public V getOrDefault​(java.lang.Object key,
                              V defaultValue)
        Returns the value to which the specified key is mapped, or the given default value if this map contains no mapping for the key.
        Specified by:
        getOrDefault in interface java.util.concurrent.ConcurrentMap<K,​V>
        Specified by:
        getOrDefault in interface java.util.Map<K,​V>
        Parameters:
        key - the key whose associated value is to be returned
        defaultValue - the value to return if this map contains no mapping for the given key
        Returns:
        the mapping for the key, if present; else the default value
        Throws:
        java.lang.NullPointerException - if the specified key is null
      • contains

        @Deprecated
        public boolean contains​(java.lang.Object value)
        Deprecated.
        Legacy method testing if some key maps into the specified value in this table. This method is identical in functionality to containsValue(Object), and exists solely to ensure full compatibility with class Hashtable, which supported this method prior to introduction of the Java Collections framework.
        Parameters:
        value - a value to search for
        Returns:
        true if and only if some key maps to the value argument in this table as determined by the equals method; false otherwise
        Throws:
        java.lang.NullPointerException - if the specified value is null
      • keys

        public java.util.Enumeration<K> keys()
        Returns an enumeration of the keys in this table.
        Returns:
        an enumeration of the keys in this table
        See Also:
        keySet()
      • elements

        public java.util.Enumeration<V> elements()
        Returns an enumeration of the values in this table.
        Returns:
        an enumeration of the values in this table
        See Also:
        values()
      • mappingCount

        public long mappingCount()
        Returns the number of mappings. This method should be used instead of size() because a ConcurrentHashMapV8 may contain more mappings than can be represented as an int. The value returned is an estimate; the actual count may differ if there are concurrent insertions or removals.
        Returns:
        the number of mappings
        Since:
        1.8
      • newKeySet

        public static <K> ConcurrentHashMapV8.KeySetView<K,​java.lang.Boolean> newKeySet()
        Creates a new Set backed by a ConcurrentHashMapV8 from the given type to Boolean.TRUE.
        Returns:
        the new set
        Since:
        1.8
      • newKeySet

        public static <K> ConcurrentHashMapV8.KeySetView<K,​java.lang.Boolean> newKeySet​(int initialCapacity)
        Creates a new Set backed by a ConcurrentHashMapV8 from the given type to Boolean.TRUE.
        Parameters:
        initialCapacity - The implementation performs internal sizing to accommodate this many elements.
        Returns:
        the new set
        Throws:
        java.lang.IllegalArgumentException - if the initial capacity of elements is negative
        Since:
        1.8
      • keySet

        public ConcurrentHashMapV8.KeySetView<K,​V> keySet​(V mappedValue)
        Returns a Set view of the keys in this map, using the given common mapped value for any additions (i.e., Collection.add(E) and Collection.addAll(Collection)). This is of course only appropriate if it is acceptable to use the same value for all additions from this view.
        Parameters:
        mappedValue - the mapped value to use for any additions
        Returns:
        the set view
        Throws:
        java.lang.NullPointerException - if the mappedValue is null
      • addCount

        private final void addCount​(long x,
                                    int check)
        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.
        Parameters:
        x - the count to add
        check - if <0, don't check resize, if <= 1 only check if uncontended
      • tryPresize

        private final void tryPresize​(int size)
        Tries to presize table to accommodate the given number of elements.
        Parameters:
        size - number of elements (doesn't need to be perfectly accurate)
      • treeifyBin

        private final void treeifyBin​(ConcurrentHashMapV8.Node<K,​V>[] tab,
                                      int index)
        Replaces all linked nodes in bin at given index unless table is too small, in which case resizes instead.
      • sumCount

        final long sumCount()
      • getUnsafe

        private static sun.misc.Unsafe getUnsafe()
        Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. Replace with a simple call to Unsafe.getUnsafe when integrating into a jdk.
        Returns:
        a sun.misc.Unsafe