Class ConcurrentHashMap
- All Implemented Interfaces:
Serializable
,Cloneable
,Map
- Retrievals
- Retrievals may overlap updates. (This is the same policy as
ConcurrentReaderHashMap.) Successful retrievals using get(key) and
containsKey(key) usually run without locking. Unsuccessful
retrievals (i.e., when the key is not present) do involve brief
synchronization (locking). Because retrieval operations can
ordinarily overlap with update operations (i.e., put, remove, and
their derivatives), retrievals can only be guaranteed to return the
results of the most recently completed operations holding
upon their onset. Retrieval operations may or may not return
results reflecting in-progress writing operations. However, the
retrieval operations do always return consistent results -- either
those holding before any single modification or after it, but never
a nonsense result. For aggregate operations such as putAll and
clear, concurrent reads may reflect insertion or removal of only
some entries.
Iterators and Enumerations (i.e., those returned by keySet().iterator(), entrySet().iterator(), values().iterator(), keys(), and elements()) return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They will return at most one instance of each element (via next()/nextElement()), but might or might not reflect puts and removes that have been processed since they were created. They do not throw ConcurrentModificationException. However, these iterators are designed to be used by only one thread at a time. Passing an iterator across multiple threads may lead to unpredictable results if the table is being concurrently modified.
- Updates
- This class supports a hard-wired preset concurrency
level of 32. This allows a maximum of 32 put and/or remove
operations to proceed concurrently. This level is an upper bound on
concurrency, not a guarantee, since it interacts with how
well-strewn elements are across bins of the table. (The preset
value in part reflects the fact that even on large multiprocessors,
factors other than synchronization tend to be bottlenecks when more
than 32 threads concurrently attempt updates.)
Additionally, operations triggering internal resizing and clearing
do not execute concurrently with any operation.
There is NOT any support for locking the entire table to prevent updates. This makes it imposssible, for example, to add an element only if it is not already present, since another thread may be in the process of doing the same thing. If you need such capabilities, consider instead using the ConcurrentReaderHashMap class.
This class may be used as a direct replacement for java.util.Hashtable in any application that does not rely on the ability to lock the entire table to prevent updates. As of this writing, it performs much faster than Hashtable in typical multi-threaded applications with multiple readers and writers. Like Hashtable but unlike java.util.HashMap, this class does NOT allow null to be used as a key or value.
Implementation note: A slightly faster implementation of this class will be possible once planned Java Memory Model revisions are in place.
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected static class
ConcurrentHashMap collision list entry.protected class
protected class
protected static final class
Bookkeeping for each concurrency control segment.protected class
Nested classes/interfaces inherited from class java.util.AbstractMap
AbstractMap.SimpleEntry<K,
V>, AbstractMap.SimpleImmutableEntry<K, V> -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected static final int
The number of concurrency control segments.static int
The default initial number of table slots for this table (32).static final float
The default load factor for this table (0.75) Used when not otherwise specified in constructor.protected Set
protected Set
protected final float
The load factor for the hash table.protected static final int
Mask value for indexing into segmentsprotected final ConcurrentHashMap.Segment[]
The array of concurrency control segments.protected ConcurrentHashMap.Entry[]
The hash table data.protected int
Per-segment resize threshold.protected Collection
protected int
Number of segments voting for resize. -
Constructor Summary
ConstructorsConstructorDescriptionConstructs a new, empty map with a default initial capacity and default load factor.ConcurrentHashMap
(int initialCapacity) Constructs a new, empty map with the specified initial capacity and default load factor.ConcurrentHashMap
(int initialCapacity, float loadFactor) Constructs a new, empty map with the specified initial capacity and the specified load factor.Constructs a new map with the same mappings as the given map. -
Method Summary
Modifier and TypeMethodDescriptionprotected static int
bitcount
(int w) Return the number of set bits in w.void
clear()
Removes all mappings from this map.clone()
Returns a shallow copy of this ConcurrentHashMap instance: the keys and values themselves are not cloned.boolean
Tests if some key maps into the specified value in this table.boolean
containsKey
(Object key) Tests if the specified object is a key in this table.boolean
containsValue
(Object value) Returns true if this map maps one or more keys to the specified value.elements()
Returns an enumeration of the values in this table.entrySet()
Returns a collection view of the mappings contained in this map.protected boolean
Check for equality of non-null references x and y.Returns the value to which the specified key is mapped in this table.protected static int
Return hash code for Object x.boolean
isEmpty()
Returns true if this map contains no key-value mappings.keys()
Returns an enumeration of the keys in this table.keySet()
Returns a set view of the keys contained in this map.protected ConcurrentHashMap.Entry[]
newTable
(int capacity) Create table array and set the per-segment thresholdMaps the specifiedkey
to the specifiedvalue
in this table.void
Copies all of the mappings from the specified map to this one.protected void
rehash()
Rehashes the contents of this map into a new table with a larger capacity.Removes the key (and its corresponding value) from this table.protected Object
removeCompat
(Object key, Object value) Removes the (key, value) pair from this table.protected void
resize
(int index, ConcurrentHashMap.Entry[] assumedTab) Gather all locks in order to call rehash, by recursing within synch blocks for each segment index.int
size()
Returns the number of key-value mappings in this map.values()
Returns a collection view of the values contained in this map.Methods inherited from class java.util.AbstractMap
equals, hashCode, toString
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface java.util.Map
compute, computeIfAbsent, computeIfPresent, equals, forEach, getOrDefault, hashCode, merge, putIfAbsent, remove, replace, replace, replaceAll
-
Field Details
-
table
The hash table data. -
CONCURRENCY_LEVEL
protected static final int CONCURRENCY_LEVELThe number of concurrency control segments. The value can be at most 32 since ints are used as bitsets over segments. Emprically, it doesn't seem to pay to decrease it either, so the value should be at least 32. In other words, do not redefine this :-)- See Also:
-
SEGMENT_MASK
protected static final int SEGMENT_MASKMask value for indexing into segments- See Also:
-
segments
The array of concurrency control segments. -
DEFAULT_INITIAL_CAPACITY
public static int DEFAULT_INITIAL_CAPACITYThe default initial number of table slots for this table (32). Used when not otherwise specified in constructor. -
DEFAULT_LOAD_FACTOR
public static final float DEFAULT_LOAD_FACTORThe default load factor for this table (0.75) Used when not otherwise specified in constructor.- See Also:
-
loadFactor
protected final float loadFactorThe load factor for the hash table. -
threshold
protected int thresholdPer-segment resize threshold. -
votesForResize
protected transient volatile int votesForResizeNumber of segments voting for resize. The table is doubled when 1/4 of the segments reach threshold. Volatile but updated without synch since this is just a heuristic. -
keySet
-
entrySet
-
values
-
-
Constructor Details
-
ConcurrentHashMap
public ConcurrentHashMap(int initialCapacity, float loadFactor) Constructs a new, empty map with the specified initial capacity and the specified load factor.- Parameters:
initialCapacity
- the initial capacity. The actual initial capacity is rounded to the nearest power of two.loadFactor
- the load factor threshold, used to control resizing. This value is used in an approximate way: When at least a quarter of the segments of the table reach per-segment threshold, or one of the segments itself exceeds overall threshold, the table is doubled. This will on average cause resizing when the table-wide load factor is slightly less than the threshold. If you'd like to avoid resizing, you can set this to a ridiculously large value.- Throws:
IllegalArgumentException
- if the load factor is nonpositive.
-
ConcurrentHashMap
public ConcurrentHashMap(int initialCapacity) Constructs a new, empty map with the specified initial capacity and default load factor.- Parameters:
initialCapacity
- the initial capacity of the ConcurrentHashMap.- Throws:
IllegalArgumentException
- if the initial maximum number of elements is less than zero.
-
ConcurrentHashMap
public ConcurrentHashMap()Constructs a new, empty map with a default initial capacity and default load factor. -
ConcurrentHashMap
Constructs a new map with the same mappings as the given map. The map is created with a capacity of twice the number of mappings in the given map or 32 (whichever is greater), and a default load factor.
-
-
Method Details
-
bitcount
protected static int bitcount(int w) Return the number of set bits in w. For a derivation of this algorithm, see "Algorithms and data structures with applications to graphics and geometry", by Jurg Nievergelt and Klaus Hinrichs, Prentice Hall, 1993. See also notes by Torsten Sillke at http://www.mathematik.uni-bielefeld.de/~sillke/PROBLEMS/bitcount -
hash
Return hash code for Object x. Since we are using power-of-two tables, it is worth the effort to improve hashcode via the same multiplicative scheme as used in IdentityHashMap. -
eq
Check for equality of non-null references x and y. -
newTable
Create table array and set the per-segment threshold -
size
public int size()Returns the number of key-value mappings in this map.- Specified by:
size
in interfaceMap
- Overrides:
size
in classAbstractMap
- Returns:
- the number of key-value mappings in this map.
-
isEmpty
public boolean isEmpty()Returns true if this map contains no key-value mappings.- Specified by:
isEmpty
in interfaceMap
- Overrides:
isEmpty
in classAbstractMap
- Returns:
- true if this map contains no key-value mappings.
-
get
Returns the value to which the specified key is mapped in this table.- Specified by:
get
in interfaceMap
- Overrides:
get
in classAbstractMap
- Parameters:
key
- a key in the table.- Returns:
- the value to which the key is mapped in this table;
null
if the key is not mapped to any value in this table. - Throws:
NullPointerException
- if the key isnull
.- See Also:
-
containsKey
Tests if the specified object is a key in this table.- Specified by:
containsKey
in interfaceMap
- Overrides:
containsKey
in classAbstractMap
- 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:
NullPointerException
- if the key isnull
.- See Also:
-
put
Maps the specifiedkey
to the specifiedvalue
in this table. Neither the key nor the value can benull
. (Note that this policy is the same as for java.util.Hashtable, but unlike java.util.HashMap, which does accept nulls as valid keys and values.)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
- Overrides:
put
in classAbstractMap
- Parameters:
key
- the table key.value
- the value.- Returns:
- the previous value of the specified key in this table,
or
null
if it did not have one. - Throws:
NullPointerException
- if the key or value isnull
.- See Also:
-
resize
Gather all locks in order to call rehash, by recursing within synch blocks for each segment index.- Parameters:
index
- the current segment. initially call value must be 0assumedTab
- the state of table on first call to resize. If this changes on any call, the attempt is aborted because the table has already been resized by another thread.
-
rehash
protected void rehash()Rehashes the contents of this map into a new table with a larger capacity. -
remove
Removes the key (and its corresponding value) from this table. This method does nothing if the key is not in the table.- Specified by:
remove
in interfaceMap
- Overrides:
remove
in classAbstractMap
- Parameters:
key
- the key that needs to be removed.- Returns:
- the value to which the key had been mapped in this table,
or
null
if the key did not have a mapping. - Throws:
NullPointerException
- if the key isnull
.
-
removeCompat
Removes the (key, value) pair from this table. This method does nothing if the key is not in the table, or if the key is associated with a different value. This method is needed by EntrySet.- Parameters:
key
- the key that needs to be removed.value
- the associated value. If the value is null, it means "any value".- Returns:
- the value to which the key had been mapped in this table,
or
null
if the key did not have a mapping. - Throws:
NullPointerException
- if the key isnull
.
-
containsValue
Returns true if this map maps one or more keys to the specified value. Note: This method requires a full internal traversal of the hash table, and so is much slower than method containsKey.- Specified by:
containsValue
in interfaceMap
- Overrides:
containsValue
in classAbstractMap
- 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 value isnull
.
-
contains
Tests if some key maps into the specified value in this table. This operation is more expensive than thecontainsKey
method.Note that this method is identical in functionality to containsValue, (which is part of the Map interface in the 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 the equals method;false
otherwise.- Throws:
NullPointerException
- if the value isnull
.- See Also:
-
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.- Specified by:
putAll
in interfaceMap
- Overrides:
putAll
in classAbstractMap
- Parameters:
t
- Mappings to be stored in this map.
-
clear
public void clear()Removes all mappings from this map.- Specified by:
clear
in interfaceMap
- Overrides:
clear
in classAbstractMap
-
clone
Returns a shallow copy of this ConcurrentHashMap instance: the keys and values themselves are not cloned.- Overrides:
clone
in classAbstractMap
- Returns:
- a shallow copy of this map.
-
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.- Specified by:
keySet
in interfaceMap
- Overrides:
keySet
in classAbstractMap
- Returns:
- a set view of the keys contained in this map.
-
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.- Specified by:
values
in interfaceMap
- Overrides:
values
in classAbstractMap
- Returns:
- a collection view of the values contained in this map.
-
entrySet
Returns a collection view of the mappings contained in this map. Each element in the returned collection is a Map.Entry. 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 the map, via the Iterator.remove, Collection.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.- Specified by:
entrySet
in interfaceMap
- Specified by:
entrySet
in classAbstractMap
- Returns:
- a collection view of the mappings contained in this map.
-
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. Use the Enumeration methods on the returned object to fetch the elements sequentially.- Returns:
- an enumeration of the values in this table.
- See Also:
-