Class ConcurrentHashMapV8<K,V>
- java.lang.Object
-
- java.util.AbstractMap<K,V>
-
- org.glassfish.jersey.internal.util.collection.ConcurrentHashMapV8<K,V>
-
- Type Parameters:
K
- the type of keys maintained by this mapV
- 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 asHashtable
, and includes versions of methods corresponding to each method ofHashtable
. 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 withHashtable
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 (includingput
andremove
). 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 asputAll
andclear
, 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 throwConcurrentModificationException
. However, iterators are designed to be used by only one thread at a time. Bear in mind that the results of aggregate status methods includingsize
,isEmpty
, andcontainsValue
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 optionalloadFactor
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 expectedconcurrencyLevel
as an additional hint for internal sizing. Note that using many keys with exactly the samehashCode()
is a sure way to slow down performance of any hash table. To ameliorate impact, when keys areComparable
, this class may use comparison order among keys to help break ties.A
Set
projection of a ConcurrentHashMapV8 may be created (usingnewKeySet()
ornewKeySet(int)
), or viewed (usingkeySet(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
andIterator
interfaces.Like
Hashtable
but unlikeHashMap
, this class does not allownull
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 methodsetValue
.- 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 ofLong.MAX_VALUE
suppresses all parallelism. Using a value of1
results in maximal parallelism by partitioning into enough subtasks to fully utilize theForkJoinPool#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 Classes Modifier and Type Class Description (package private) static class
ConcurrentHashMapV8.BaseIterator<K,V>
Base of key, value, and entry Iterators.(package private) static class
ConcurrentHashMapV8.CollectionView<K,V,E>
Base class for views.(package private) static class
ConcurrentHashMapV8.CounterCell
(package private) static class
ConcurrentHashMapV8.CounterHashCode
Holder for the thread-local hash code determining which CounterCell to use.(package private) static class
ConcurrentHashMapV8.EntryIterator<K,V>
(package private) static class
ConcurrentHashMapV8.EntrySetView<K,V>
A view of a ConcurrentHashMapV8 as aSet
of (key, value) entries.(package private) static class
ConcurrentHashMapV8.ForwardingNode<K,V>
A node inserted at head of bins during transfer operations.(package private) static class
ConcurrentHashMapV8.KeyIterator<K,V>
static class
ConcurrentHashMapV8.KeySetView<K,V>
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 class
ConcurrentHashMapV8.MapEntry<K,V>
Exported Entry for EntryIterator(package private) static class
ConcurrentHashMapV8.Node<K,V>
Key-value entry.(package private) static class
ConcurrentHashMapV8.ReservationNode<K,V>
A place-holder node used in computeIfAbsent and compute(package private) static class
ConcurrentHashMapV8.Segment<K,V>
Stripped-down version of helper class used in previous version, declared for the sake of serialization compatibility(package private) static class
ConcurrentHashMapV8.Traverser<K,V>
Encapsulates traversal for methods such as containsValue; also serves as a base class for other iterators and spliterators.(package private) static class
ConcurrentHashMapV8.TreeBin<K,V>
TreeNodes used at the heads of bins.(package private) static class
ConcurrentHashMapV8.TreeNode<K,V>
Nodes for use in TreeBins(package private) static class
ConcurrentHashMapV8.ValueIterator<K,V>
(package private) static class
ConcurrentHashMapV8.ValuesView<K,V>
A view of a ConcurrentHashMapV8 as aCollection
of values, in which additions are disabled.
-
Field Summary
Fields Modifier and Type Field Description private static long
ABASE
private static int
ASHIFT
private long
baseCount
Base counter value, used mainly when there is no contention, but also as a fallback during table initialization races.private static long
BASECOUNT
private int
cellsBusy
Spinlock (locked via CAS) used when resizing and/or creating CounterCells.private static long
CELLSBUSY
private static long
CELLVALUE
private ConcurrentHashMapV8.CounterCell[]
counterCells
Table of counter cells.(package private) static java.util.concurrent.atomic.AtomicInteger
counterHashCodeGenerator
Generates initial value for per-thread CounterHashCodes.private static int
DEFAULT_CAPACITY
The default initial table capacity.private static int
DEFAULT_CONCURRENCY_LEVEL
The default concurrency level for this table.private ConcurrentHashMapV8.EntrySetView<K,V>
entrySet
(package private) static int
HASH_BITS
private ConcurrentHashMapV8.KeySetView<K,V>
keySet
private static float
LOAD_FACTOR
The load factor for this table.(package private) static int
MAX_ARRAY_SIZE
The largest possible (non-power of two) array size.private static int
MAXIMUM_CAPACITY
The largest possible table capacity.private static int
MIN_TRANSFER_STRIDE
Minimum number of rebinnings per transfer step.(package private) static int
MIN_TREEIFY_CAPACITY
The smallest table capacity for which bins may be treeified.(package private) static int
MOVED
(package private) static int
NCPU
Number of CPUS, to place bounds on some sizingsprivate ConcurrentHashMapV8.Node<K,V>[]
nextTable
The next table to use; non-null only while resizing.(package private) static int
RESERVED
(package private) static int
SEED_INCREMENT
Increment for counterHashCodeGenerator.private static java.io.ObjectStreamField[]
serialPersistentFields
For serialization compatibility.private static long
serialVersionUID
private int
sizeCtl
Table initialization and resizing control.private static long
SIZECTL
(package private) ConcurrentHashMapV8.Node<K,V>[]
table
The array of bins.(package private) static java.lang.ThreadLocal<ConcurrentHashMapV8.CounterHashCode>
threadCounterHashCode
Per-thread counter hash codes.private int
transferIndex
The next table index (plus one) to split while resizing.private static long
TRANSFERINDEX
private int
transferOrigin
The least available table index to split while resizing.private static long
TRANSFERORIGIN
(package private) static int
TREEBIN
(package private) static int
TREEIFY_THRESHOLD
The bin count threshold for using a tree rather than list for a bin.private static sun.misc.Unsafe
U
(package private) static int
UNTREEIFY_THRESHOLD
The bin count threshold for untreeifying a (split) bin during a resize operation.private ConcurrentHashMapV8.ValuesView<K,V>
values
-
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>
booleancasTabAt(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)
Returnstrue
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 aSet
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, ornull
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 thisMap
, 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 aSet
view of the keys contained in this map.ConcurrentHashMapV8.KeySetView<K,V>
keySet(V mappedValue)
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
mappingCount()
Returns the number of mappings.static <K> ConcurrentHashMapV8.KeySetView<K,java.lang.Boolean>
newKeySet()
Creates a newSet
backed by a ConcurrentHashMapV8 from the given type toBoolean.TRUE
.static <K> ConcurrentHashMapV8.KeySetView<K,java.lang.Boolean>
newKeySet(int initialCapacity)
Creates a newSet
backed by a ConcurrentHashMapV8 from the given type toBoolean.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 putIfAbsentprivate 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>
voidsetTabAt(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 aCollection
view of the values contained in this map.private void
writeObject(java.io.ObjectOutputStream s)
Saves the state of theConcurrentHashMapV8
instance to a stream (i.e., serializes it).
-
-
-
Field Detail
-
serialVersionUID
private static final long serialVersionUID
- See Also:
- Constant Field Values
-
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 asn - (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
-
MOVED
static final int MOVED
- See Also:
- Constant Field Values
-
TREEBIN
static final int TREEBIN
- See Also:
- Constant Field Values
-
RESERVED
static final int RESERVED
- See Also:
- Constant Field Values
-
HASH_BITS
static final int HASH_BITS
- 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.
-
counterCells
private transient volatile ConcurrentHashMapV8.CounterCell[] counterCells
Table of counter cells. When non-null, size is a power of 2.
-
keySet
private transient ConcurrentHashMapV8.KeySetView<K,V> keySet
-
values
private transient ConcurrentHashMapV8.ValuesView<K,V> values
-
entrySet
private transient ConcurrentHashMapV8.EntrySetView<K,V> entrySet
-
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 sizeconcurrencyLevel
- 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.
-
tabAt
static final <K,V> ConcurrentHashMapV8.Node<K,V> tabAt(ConcurrentHashMapV8.Node<K,V>[] tab, int i)
-
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
public V get(java.lang.Object key)
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.)
-
containsKey
public boolean containsKey(java.lang.Object key)
Tests if the specified object is a key in this table.- Specified by:
containsKey
in interfacejava.util.Map<K,V>
- Overrides:
containsKey
in classjava.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 theequals
method;false
otherwise- Throws:
java.lang.NullPointerException
- if the specified key is null
-
containsValue
public boolean containsValue(java.lang.Object value)
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 interfacejava.util.Map<K,V>
- Overrides:
containsValue
in classjava.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 interfacejava.util.Map<K,V>
- Overrides:
put
in classjava.util.AbstractMap<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:
java.lang.NullPointerException
- if the specified key or value is null
-
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.
-
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 interfacejava.util.Map<K,V>
- Overrides:
remove
in classjava.util.AbstractMap<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:
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.
-
keySet
public ConcurrentHashMapV8.KeySetView<K,V> 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
public java.util.Collection<V> 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
public java.util.Set<java.util.Map.Entry<K,V>> 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
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.
-
equals
public boolean equals(java.lang.Object o)
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
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException
Saves the state of theConcurrentHashMapV8
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 foundjava.io.IOException
- if an I/O error occurs
-
putIfAbsent
public V putIfAbsent(K key, V value)
- Specified by:
putIfAbsent
in interfacejava.util.concurrent.ConcurrentMap<K,V>
- Specified by:
putIfAbsent
in interfacejava.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)
-
replace
public V replace(K key, V value)
- Specified by:
replace
in interfacejava.util.concurrent.ConcurrentMap<K,V>
- Specified by:
replace
in interfacejava.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 interfacejava.util.concurrent.ConcurrentMap<K,V>
- Specified by:
getOrDefault
in interfacejava.util.Map<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:
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 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:
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 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
public static <K> ConcurrentHashMapV8.KeySetView<K,java.lang.Boolean> newKeySet()
Creates a newSet
backed by a ConcurrentHashMapV8 from the given type toBoolean.TRUE
.- Returns:
- the new set
- Since:
- 1.8
-
newKeySet
public static <K> ConcurrentHashMapV8.KeySetView<K,java.lang.Boolean> newKeySet(int initialCapacity)
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:
java.lang.IllegalArgumentException
- if the initial capacity of elements is negative- Since:
- 1.8
-
keySet
public ConcurrentHashMapV8.KeySetView<K,V> keySet(V mappedValue)
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:
java.lang.NullPointerException
- if the mappedValue is null
-
initTable
private final ConcurrentHashMapV8.Node<K,V>[] 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 <0, don't check resize, if <= 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
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.
-
untreeify
static <K,V> ConcurrentHashMapV8.Node<K,V> untreeify(ConcurrentHashMapV8.Node<K,V> b)
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
-
-