Class ConcurrentHashMapV8<K,V>
- Type Parameters:
K
- the type of keys maintained by this mapV
- the type of mapped values
- All Implemented Interfaces:
Serializable
,ConcurrentMap<K,
,V> Map<K,
V>
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.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescription(package private) static class
Base of key, value, and entry Iterators.(package private) static class
Base class for views.(package private) static final class
(package private) static final class
Holder for the thread-local hash code determining which CounterCell to use.(package private) static final class
(package private) static final class
A view of a ConcurrentHashMapV8 as aSet
of (key, value) entries.(package private) static final class
A node inserted at head of bins during transfer operations.(package private) static final class
static class
A view of a ConcurrentHashMapV8 as aSet
of keys, in which additions may optionally be enabled by mapping to a common value.(package private) static final class
Exported Entry for EntryIterator(package private) static class
Key-value entry.(package private) static final class
A place-holder node used in computeIfAbsent and compute(package private) static class
Stripped-down version of helper class used in previous version, declared for the sake of serialization compatibility(package private) static class
Encapsulates traversal for methods such as containsValue; also serves as a base class for other iterators and spliterators.(package private) static final class
TreeNodes used at the heads of bins.(package private) static final class
Nodes for use in TreeBins(package private) static final class
(package private) static final class
A view of a ConcurrentHashMapV8 as aCollection
of values, in which additions are disabled.Nested classes/interfaces inherited from class java.util.AbstractMap
AbstractMap.SimpleEntry<K,
V>, AbstractMap.SimpleImmutableEntry<K, V> -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final long
private static final int
private long
Base counter value, used mainly when there is no contention, but also as a fallback during table initialization races.private static final long
private int
Spinlock (locked via CAS) used when resizing and/or creating CounterCells.private static final long
private static final long
private ConcurrentHashMapV8.CounterCell[]
Table of counter cells.(package private) static final AtomicInteger
Generates initial value for per-thread CounterHashCodes.private static final int
The default initial table capacity.private static final int
The default concurrency level for this table.private ConcurrentHashMapV8.EntrySetView
<K, V> (package private) static final int
private ConcurrentHashMapV8.KeySetView
<K, V> private static final float
The load factor for this table.(package private) static final int
The largest possible (non-power of two) array size.private static final int
The largest possible table capacity.private static final int
Minimum number of rebinnings per transfer step.(package private) static final int
The smallest table capacity for which bins may be treeified.(package private) static final int
(package private) static final int
Number of CPUS, to place bounds on some sizingsprivate ConcurrentHashMapV8.Node<K,
V>[] The next table to use; non-null only while resizing.(package private) static final int
(package private) static final int
Increment for counterHashCodeGenerator.private static final ObjectStreamField[]
For serialization compatibility.private static final long
private int
Table initialization and resizing control.private static final long
(package private) ConcurrentHashMapV8.Node<K,
V>[] The array of bins.(package private) static final ThreadLocal
<ConcurrentHashMapV8.CounterHashCode> Per-thread counter hash codes.private int
The next table index (plus one) to split while resizing.private static final long
private int
The least available table index to split while resizing.private static final long
(package private) static final int
(package private) static final int
The bin count threshold for using a tree rather than list for a bin.private static final sun.misc.Unsafe
(package private) static final int
The bin count threshold for untreeifying a (split) bin during a resize operation.private ConcurrentHashMapV8.ValuesView
<K, V> -
Constructor Summary
ConstructorsConstructorDescriptionCreates 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
(Map<? extends K, ? extends V> m) Creates a new map with the same mappings as the given map. -
Method Summary
Modifier and TypeMethodDescriptionprivate final void
addCount
(long x, int check) Adds to count, and if table is too small and not already resizing, initiates transfer.(package private) static final <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 Class
<?> Returns x's Class if it is of the form "class C implements Comparable", else null. (package private) static int
compareComparables
(Class<?> kc, Object k, Object x) Returns k.compareTo(x) if x matches kc (k's screened comparable class), else 0.boolean
Deprecated.boolean
containsKey
(Object key) Tests if the specified object is a key in this table.boolean
containsValue
(Object value) Returnstrue
if this map maps one or more keys to the specified value.elements()
Returns an enumeration of the values in this table.entrySet()
Returns aSet
view of the mappings contained in this map.boolean
Compares the specified object with this map for equality.private final void
fullAddCount
(long x, ConcurrentHashMapV8.CounterHashCode hc, boolean wasUncontended) Returns the value to which the specified key is mapped, ornull
if this map contains no mapping for the key.getOrDefault
(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
Returns a sun.misc.Unsafe.int
hashCode()
Returns the hash code value for thisMap
, i.e., the sum of, for each key-value pair in the map,key.hashCode() ^ value.hashCode()
.(package private) final ConcurrentHashMapV8.Node<K,
V>[] helpTransfer
(ConcurrentHashMapV8.Node<K, V>[] tab, ConcurrentHashMapV8.Node<K, V> f) Helps transfer if a resize is in progress.private final ConcurrentHashMapV8.Node<K,
V>[] Initializes table, using the size recorded in sizeCtl.boolean
isEmpty()
keys()
Returns an enumeration of the keys in this table.keySet()
Returns aSet
view of the keys contained in this map.Returns aSet
view of the keys in this map, using the given common mapped value for any additions (i.e.,Collection.add(E)
andCollection.addAll(Collection)
).long
Returns the number of mappings.static <K> ConcurrentHashMapV8.KeySetView
<K, Boolean> Creates a newSet
backed by a ConcurrentHashMapV8 from the given type toBoolean.TRUE
.static <K> ConcurrentHashMapV8.KeySetView
<K, Boolean> newKeySet
(int initialCapacity) Creates a newSet
backed by a ConcurrentHashMapV8 from the given type toBoolean.TRUE
.Maps the specified key to the specified value in this table.void
Copies all of the mappings from the specified map to this one.putIfAbsent
(K key, V value) (package private) final V
Implementation for put and putIfAbsentprivate void
Reconstitutes the instance from a stream (that is, deserializes it).Removes the key (and its corresponding value) from this map.boolean
boolean
(package private) final V
replaceNode
(Object key, V value, 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 final <K,
V> void setTabAt
(ConcurrentHashMapV8.Node<K, V>[] tab, int i, ConcurrentHashMapV8.Node<K, V> v) int
size()
(package private) static final int
spread
(int h) Spreads (XORs) higher bits of hash to lower and also forces top bit to 0.(package private) final long
sumCount()
(package private) static final <K,
V> ConcurrentHashMapV8.Node <K, V> tabAt
(ConcurrentHashMapV8.Node<K, V>[] tab, int i) private static final int
tableSizeFor
(int c) Returns a power of two table size for the given desired capacity.toString()
Returns a string representation of this map.private final 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 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.private final 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.values()
Returns aCollection
view of the values contained in this map.private void
Saves the state of theConcurrentHashMapV8
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 Details
-
serialVersionUID
private static final long serialVersionUID- See Also:
-
MAXIMUM_CAPACITY
private static final int MAXIMUM_CAPACITYThe largest possible table capacity. This value must be exactly 1invalid input: '<'invalid input: '<'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:
-
DEFAULT_CAPACITY
private static final int DEFAULT_CAPACITYThe default initial table capacity. Must be a power of 2 (i.e., at least 1) and at most MAXIMUM_CAPACITY.- See Also:
-
MAX_ARRAY_SIZE
static final int MAX_ARRAY_SIZEThe largest possible (non-power of two) array size. Needed by toArray and related methods.- See Also:
-
DEFAULT_CONCURRENCY_LEVEL
private static final int DEFAULT_CONCURRENCY_LEVELThe default concurrency level for this table. Unused but defined for compatibility with previous versions of this class.- See Also:
-
LOAD_FACTOR
private static final float LOAD_FACTORThe 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 asn - (n >>> 2)
for the associated resizing threshold.- See Also:
-
TREEIFY_THRESHOLD
static final int TREEIFY_THRESHOLDThe 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:
-
UNTREEIFY_THRESHOLD
static final int UNTREEIFY_THRESHOLDThe 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:
-
MIN_TREEIFY_CAPACITY
static final int MIN_TREEIFY_CAPACITYThe 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:
-
MIN_TRANSFER_STRIDE
private static final int MIN_TRANSFER_STRIDEMinimum 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:
-
MOVED
static final int MOVED- See Also:
-
TREEBIN
static final int TREEBIN- See Also:
-
RESERVED
static final int RESERVED- See Also:
-
HASH_BITS
static final int HASH_BITS- See Also:
-
NCPU
static final int NCPUNumber of CPUS, to place bounds on some sizings -
serialPersistentFields
For serialization compatibility. -
table
The array of bins. Lazily initialized upon first insertion. Size is always a power of two. Accessed directly by iterators. -
nextTable
The next table to use; non-null only while resizing. -
baseCount
private transient volatile long baseCountBase 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 sizeCtlTable 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 transferIndexThe next table index (plus one) to split while resizing. -
transferOrigin
private transient volatile int transferOriginThe least available table index to split while resizing. -
cellsBusy
private transient volatile int cellsBusySpinlock (locked via CAS) used when resizing and/or creating CounterCells. -
counterCells
Table of counter cells. When non-null, size is a power of 2. -
keySet
-
values
-
entrySet
-
counterHashCodeGenerator
Generates initial value for per-thread CounterHashCodes. -
SEED_INCREMENT
static final int SEED_INCREMENTIncrement for counterHashCodeGenerator. See class ThreadLocal for explanation.- See Also:
-
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 Details
-
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:
IllegalArgumentException
- if the initial capacity of elements is negative
-
ConcurrentHashMapV8
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:
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 sizeconcurrencyLevel
- 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
-
-
Method Details
-
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
Returns x's Class if it is of the form "class C implements Comparable", else null. -
compareComparables
Returns k.compareTo(x) if x matches kc (k's screened comparable class), else 0. -
tabAt
-
casTabAt
static final <K,V> boolean casTabAt(ConcurrentHashMapV8.Node<K, V>[] tab, int i, ConcurrentHashMapV8.Node<K, V> c, ConcurrentHashMapV8.Node<K, V> v) -
setTabAt
static final <K,V> void setTabAt(ConcurrentHashMapV8.Node<K, V>[] tab, int i, ConcurrentHashMapV8.Node<K, V> v) -
size
public int size() -
isEmpty
public boolean isEmpty() -
get
Returns the value to which the specified key is mapped, ornull
if this map contains no mapping for the key.More formally, if this map contains a mapping from a key
k
to a valuev
such thatkey.equals(k)
, then this method returnsv
; otherwise it returnsnull
. (There can be at most one such mapping.)- Specified by:
get
in interfaceMap<K,
V> - Overrides:
get
in classAbstractMap<K,
V> - Throws:
NullPointerException
- if the specified key is null
-
containsKey
Tests if the specified object is a key in this table.- Specified by:
containsKey
in interfaceMap<K,
V> - Overrides:
containsKey
in classAbstractMap<K,
V> - Parameters:
key
- possible key- Returns:
true
if and only if the specified object is a key in this table, as determined by theequals
method;false
otherwise- Throws:
NullPointerException
- if the specified key is null
-
containsValue
Returnstrue
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 methodcontainsKey
.- Specified by:
containsValue
in interfaceMap<K,
V> - Overrides:
containsValue
in classAbstractMap<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:
NullPointerException
- if the specified value is null
-
put
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 interfaceMap<K,
V> - Overrides:
put
in classAbstractMap<K,
V> - Parameters:
key
- key with which the specified value is to be associatedvalue
- value to be associated with the specified key- Returns:
- the previous value associated with
key
, ornull
if there was no mapping forkey
- Throws:
NullPointerException
- if the specified key or value is null
-
putVal
Implementation for put and putIfAbsent -
putAll
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. -
remove
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 interfaceMap<K,
V> - Overrides:
remove
in classAbstractMap<K,
V> - Parameters:
key
- the key that needs to be removed- Returns:
- the previous value associated with
key
, ornull
if there was no mapping forkey
- Throws:
NullPointerException
- if the specified key is null
-
replaceNode
Implementation for the four public remove/replace methods: Replaces node value with v, conditional upon match of cv if non-null. If resulting value is null, delete. -
clear
public void clear()Removes all of the mappings from this map. -
keySet
Returns aSet
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 theIterator.remove
,Set.remove
,removeAll
,retainAll
, andclear
operations. It does not support theadd
oraddAll
operations.The view's
iterator
is a "weakly consistent" iterator that will never throwConcurrentModificationException
, 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. -
values
Returns aCollection
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 theIterator.remove
,Collection.remove
,removeAll
,retainAll
, andclear
operations. It does not support theadd
oraddAll
operations.The view's
iterator
is a "weakly consistent" iterator that will never throwConcurrentModificationException
, 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. -
entrySet
Returns aSet
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 theIterator.remove
,Set.remove
,removeAll
,retainAll
, andclear
operations.The view's
iterator
is a "weakly consistent" iterator that will never throwConcurrentModificationException
, 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. -
hashCode
public int hashCode()Returns the hash code value for thisMap
, i.e., the sum of, for each key-value pair in the map,key.hashCode() ^ value.hashCode()
. -
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 classAbstractMap<K,
V> - Returns:
- a string representation of this map
-
equals
Compares the specified object with this map for equality. Returnstrue
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. -
writeObject
Saves the state of theConcurrentHashMapV8
instance to a stream (i.e., serializes it).- Parameters:
s
- the stream- Throws:
IOException
- if an I/O error occurs
-
readObject
Reconstitutes the instance from a stream (that is, deserializes it).- Parameters:
s
- the stream- Throws:
ClassNotFoundException
- if the class of a serialized object could not be foundIOException
- if an I/O error occurs
-
putIfAbsent
- Specified by:
putIfAbsent
in interfaceConcurrentMap<K,
V> - Specified by:
putIfAbsent
in interfaceMap<K,
V> - Returns:
- the previous value associated with the specified key,
or
null
if there was no mapping for the key - Throws:
NullPointerException
- if the specified key or value is null
-
remove
- Specified by:
remove
in interfaceConcurrentMap<K,
V> - Specified by:
remove
in interfaceMap<K,
V> - Throws:
NullPointerException
- if the specified key is null
-
replace
- Specified by:
replace
in interfaceConcurrentMap<K,
V> - Specified by:
replace
in interfaceMap<K,
V> - Throws:
NullPointerException
- if any of the arguments are null
-
replace
- Specified by:
replace
in interfaceConcurrentMap<K,
V> - Specified by:
replace
in interfaceMap<K,
V> - Returns:
- the previous value associated with the specified key,
or
null
if there was no mapping for the key - Throws:
NullPointerException
- if the specified key or value is null
-
getOrDefault
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 interfaceConcurrentMap<K,
V> - Specified by:
getOrDefault
in interfaceMap<K,
V> - Parameters:
key
- the key whose associated value is to be returneddefaultValue
- 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:
NullPointerException
- if the specified key is null
-
contains
Deprecated.Legacy method testing if some key maps into the specified value in this table. This method is identical in functionality tocontainsValue(Object)
, and exists solely to ensure full compatibility with classHashtable
, 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 thevalue
argument in this table as determined by theequals
method;false
otherwise- Throws:
NullPointerException
- if the specified value is null
-
keys
Returns an enumeration of the keys in this table.- Returns:
- an enumeration of the keys in this table
- See Also:
-
elements
Returns an enumeration of the values in this table.- Returns:
- an enumeration of the values in this table
- See Also:
-
mappingCount
public long mappingCount()Returns the number of mappings. This method should be used instead ofsize()
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
Creates a newSet
backed by a ConcurrentHashMapV8 from the given type toBoolean.TRUE
.- Returns:
- the new set
- Since:
- 1.8
-
newKeySet
Creates a newSet
backed by a ConcurrentHashMapV8 from the given type toBoolean.TRUE
.- Parameters:
initialCapacity
- The implementation performs internal sizing to accommodate this many elements.- Returns:
- the new set
- Throws:
IllegalArgumentException
- if the initial capacity of elements is negative- Since:
- 1.8
-
keySet
Returns aSet
view of the keys in this map, using the given common mapped value for any additions (i.e.,Collection.add(E)
andCollection.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:
NullPointerException
- if the mappedValue is null
-
initTable
Initializes table, using the size recorded in sizeCtl. -
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 addcheck
- if invalid input: '<'0, don't check resize, if invalid input: '<'= 1 only check if uncontended
-
helpTransfer
final ConcurrentHashMapV8.Node<K,V>[] helpTransfer(ConcurrentHashMapV8.Node<K, V>[] tab, ConcurrentHashMapV8.Node<K, V> f) Helps transfer if a resize is in progress. -
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)
-
transfer
private final void transfer(ConcurrentHashMapV8.Node<K, V>[] tab, ConcurrentHashMapV8.Node<K, V>[] nextTab) Moves and/or copies the nodes in each bin to new table. See above for explanation. -
treeifyBin
Replaces all linked nodes in bin at given index unless table is too small, in which case resizes instead. -
untreeify
Returns a list on non-TreeNodes replacing those in given list. -
sumCount
final long sumCount() -
fullAddCount
private final void fullAddCount(long x, ConcurrentHashMapV8.CounterHashCode hc, boolean wasUncontended) -
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
-