ConcurrentHashMappublic class ConcurrentHashMap extends AbstractMap implements Serializable, ConcurrentMapA hash table supporting full concurrency of retrievals and
adjustable expected concurrency for updates. This class obeys the
same functional specification as {@link java.util.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. 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 {@link ConcurrentModificationException}.
However, iterators are designed to be used by only one thread at a time.
The allowed concurrency among update operations is guided by
the optional concurrencyLevel constructor argument
(default 16), which is used as a hint for internal sizing. The
table is internally partitioned to try to permit the indicated
number of concurrent updates without contention. Because placement
in hash tables is essentially random, the actual concurrency will
vary. Ideally, you should choose a value to accommodate as many
threads as will ever concurrently modify the table. Using a
significantly higher value than you need can waste space and time,
and a significantly lower value can lead to thread contention. But
overestimates and underestimates within an order of magnitude do
not usually have much noticeable impact. A value of one is
appropriate when it is known that only one thread will modify and
all others will only read. Also, resizing this or any other kind of
hash table is a relatively slow operation, so, when possible, it is
a good idea to provide estimates of expected table sizes in
constructors.
This class and its views and iterators implement all of the
optional methods of the {@link Map} and {@link Iterator}
interfaces.
Like {@link Hashtable} but unlike {@link HashMap}, this class
does not allow null to be used as a key or value.
This class is a member of the
Java Collections Framework. |
Fields Summary |
---|
private static final long | serialVersionUID | static final int | DEFAULT_INITIAL_CAPACITYThe default initial capacity for this table,
used when not otherwise specified in a constructor. | static final float | DEFAULT_LOAD_FACTORThe default load factor for this table, used when not
otherwise specified in a constructor. | static final int | DEFAULT_CONCURRENCY_LEVELThe default concurrency level for this table, used when not
otherwise specified in a constructor. | static final int | MAXIMUM_CAPACITYThe maximum capacity, used if a higher value is implicitly
specified by either of the constructors with arguments. MUST
be a power of two <= 1<<30 to ensure that entries are indexable
using ints. | static final int | MAX_SEGMENTSThe maximum number of segments to allow; used to bound
constructor arguments. | static final int | RETRIES_BEFORE_LOCKNumber of unsynchronized retries in size and containsValue
methods before resorting to locking. This is used to avoid
unbounded retries if tables undergo continuous modification
which would make it impossible to obtain an accurate result. | final int | segmentMaskMask value for indexing into segments. The upper bits of a
key's hash code are used to choose the segment. | final int | segmentShiftShift value for indexing within segments. | final Segment[] | segmentsThe segments, each of which is a specialized hash table | transient Set | keySet | transient Set | entrySet | transient Collection | values |
Constructors Summary |
---|
public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel)Creates a new, empty map with the specified initial
capacity, load factor and concurrency level.
if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
if (concurrencyLevel > MAX_SEGMENTS)
concurrencyLevel = MAX_SEGMENTS;
// Find power-of-two sizes best matching arguments
int sshift = 0;
int ssize = 1;
while (ssize < concurrencyLevel) {
++sshift;
ssize <<= 1;
}
segmentShift = 32 - sshift;
segmentMask = ssize - 1;
this.segments = Segment.newArray(ssize);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
int c = initialCapacity / ssize;
if (c * ssize < initialCapacity)
++c;
int cap = 1;
while (cap < c)
cap <<= 1;
for (int i = 0; i < this.segments.length; ++i)
this.segments[i] = new Segment<K,V>(cap, loadFactor);
| public ConcurrentHashMap(int initialCapacity, float loadFactor)Creates a new, empty map with the specified initial capacity
and load factor and with the default concurrencyLevel (16).
this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL);
| public ConcurrentHashMap(int initialCapacity)Creates a new, empty map with the specified initial capacity,
and with default load factor (0.75) and concurrencyLevel (16).
this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
| public ConcurrentHashMap()Creates a new, empty map with a default initial capacity (16),
load factor (0.75) and concurrencyLevel (16).
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
| public ConcurrentHashMap(Map m)Creates a new map with the same mappings as the given map.
The map is created with a capacity of 1.5 times the number
of mappings in the given map or 16 (whichever is greater),
and a default load factor (0.75) and concurrencyLevel (16).
this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
DEFAULT_INITIAL_CAPACITY),
DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
putAll(m);
|
Methods Summary |
---|
public void | clear()Removes all of the mappings from this map.
for (int i = 0; i < segments.length; ++i)
segments[i].clear();
| public boolean | contains(java.lang.Object value)Legacy method testing if some key maps into the specified value
in this table. This method is identical in functionality to
{@link #containsValue}, and exists solely to ensure
full compatibility with class {@link java.util.Hashtable},
which supported this method prior to introduction of the
Java Collections framework.
return containsValue(value);
| public boolean | containsKey(java.lang.Object key)Tests if the specified object is a key in this table.
int hash = hash(key.hashCode());
return segmentFor(hash).containsKey(key, hash);
| public boolean | containsValue(java.lang.Object value)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.
if (value == null)
throw new NullPointerException();
// See explanation of modCount use above
final Segment<K,V>[] segments = this.segments;
int[] mc = new int[segments.length];
// Try a few times without locking
for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
int sum = 0;
int mcsum = 0;
for (int i = 0; i < segments.length; ++i) {
int c = segments[i].count;
mcsum += mc[i] = segments[i].modCount;
if (segments[i].containsValue(value))
return true;
}
boolean cleanSweep = true;
if (mcsum != 0) {
for (int i = 0; i < segments.length; ++i) {
int c = segments[i].count;
if (mc[i] != segments[i].modCount) {
cleanSweep = false;
break;
}
}
}
if (cleanSweep)
return false;
}
// Resort to locking all segments
for (int i = 0; i < segments.length; ++i)
segments[i].lock();
boolean found = false;
try {
for (int i = 0; i < segments.length; ++i) {
if (segments[i].containsValue(value)) {
found = true;
break;
}
}
} finally {
for (int i = 0; i < segments.length; ++i)
segments[i].unlock();
}
return found;
| public java.util.Enumeration | elements()Returns an enumeration of the values in this table.
return new ValueIterator();
| public java.util.Set | entrySet()Returns a {@link Set} view of the mappings contained in this map.
The set is backed by the map, so changes to the map are
reflected in the set, and vice-versa. The set supports element
removal, which removes the corresponding mapping from the map,
via the Iterator.remove, Set.remove,
removeAll, retainAll, and clear
operations. It does not support the add or
addAll operations.
The view's iterator is a "weakly consistent" iterator
that will never throw {@link ConcurrentModificationException},
and guarantees to traverse elements as they existed upon
construction of the iterator, and may (but is not guaranteed to)
reflect any modifications subsequent to construction.
Set<Map.Entry<K,V>> es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet());
| public V | get(java.lang.Object key)Returns the value to which the specified key is mapped,
or {@code null} if this map contains no mapping for the key.
More formally, if this map contains a mapping from a key
{@code k} to a value {@code v} such that {@code key.equals(k)},
then this method returns {@code v}; otherwise it returns
{@code null}. (There can be at most one such mapping.)
int hash = hash(key.hashCode());
return segmentFor(hash).get(key, hash);
| private static int | hash(int h)Applies a supplemental hash function to a given hashCode, which
defends against poor quality hash functions. This is critical
because ConcurrentHashMap uses power-of-two length hash tables,
that otherwise encounter collisions for hashCodes that do not
differ in lower or upper bits.
/* ---------------- Small Utilities -------------- */
// Spread bits to regularize both segment and index locations,
// using variant of single-word Wang/Jenkins hash.
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
| public boolean | isEmpty()Returns true if this map contains no key-value mappings.
final Segment<K,V>[] segments = this.segments;
/*
* We keep track of per-segment modCounts to avoid ABA
* problems in which an element in one segment was added and
* in another removed during traversal, in which case the
* table was never actually empty at any point. Note the
* similar use of modCounts in the size() and containsValue()
* methods, which are the only other methods also susceptible
* to ABA problems.
*/
int[] mc = new int[segments.length];
int mcsum = 0;
for (int i = 0; i < segments.length; ++i) {
if (segments[i].count != 0)
return false;
else
mcsum += mc[i] = segments[i].modCount;
}
// If mcsum happens to be zero, then we know we got a snapshot
// before any modifications at all were made. This is
// probably common enough to bother tracking.
if (mcsum != 0) {
for (int i = 0; i < segments.length; ++i) {
if (segments[i].count != 0 ||
mc[i] != segments[i].modCount)
return false;
}
}
return true;
| public java.util.Set | keySet()Returns a {@link Set} view of the keys contained in this map.
The set is backed by the map, so changes to the map are
reflected in the set, and vice-versa. The set supports element
removal, which removes the corresponding mapping from this map,
via the Iterator.remove, Set.remove,
removeAll, retainAll, and clear
operations. It does not support the add or
addAll operations.
The view's iterator is a "weakly consistent" iterator
that will never throw {@link ConcurrentModificationException},
and guarantees to traverse elements as they existed upon
construction of the iterator, and may (but is not guaranteed to)
reflect any modifications subsequent to construction.
Set<K> ks = keySet;
return (ks != null) ? ks : (keySet = new KeySet());
| public java.util.Enumeration | keys()Returns an enumeration of the keys in this table.
return new KeyIterator();
| 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.
if (value == null)
throw new NullPointerException();
int hash = hash(key.hashCode());
return segmentFor(hash).put(key, hash, value, false);
| public void | putAll(java.util.Map 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.
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
put(e.getKey(), e.getValue());
| public V | putIfAbsent(K key, V value){@inheritDoc}
if (value == null)
throw new NullPointerException();
int hash = hash(key.hashCode());
return segmentFor(hash).put(key, hash, value, true);
| private void | readObject(java.io.ObjectInputStream s)Reconstitute the ConcurrentHashMap instance from a
stream (i.e., deserialize it).
s.defaultReadObject();
// Initialize each segment to be minimally sized, and let grow.
for (int i = 0; i < segments.length; ++i) {
segments[i].setTable(new HashEntry[1]);
}
// Read the keys and values, and put the mappings in the table
for (;;) {
K key = (K) s.readObject();
V value = (V) s.readObject();
if (key == null)
break;
put(key, value);
}
| 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.
int hash = hash(key.hashCode());
return segmentFor(hash).remove(key, hash, null);
| public boolean | remove(java.lang.Object key, java.lang.Object value){@inheritDoc}
int hash = hash(key.hashCode());
if (value == null)
return false;
return segmentFor(hash).remove(key, hash, value) != null;
| public boolean | replace(K key, V oldValue, V newValue){@inheritDoc}
if (oldValue == null || newValue == null)
throw new NullPointerException();
int hash = hash(key.hashCode());
return segmentFor(hash).replace(key, hash, oldValue, newValue);
| public V | replace(K key, V value){@inheritDoc}
if (value == null)
throw new NullPointerException();
int hash = hash(key.hashCode());
return segmentFor(hash).replace(key, hash, value);
| final java.util.concurrent.ConcurrentHashMap$Segment | segmentFor(int hash)Returns the segment that should be used for key with given hash
return segments[(hash >>> segmentShift) & segmentMask];
| public int | size()Returns the number of key-value mappings in this map. If the
map contains more than Integer.MAX_VALUE elements, returns
Integer.MAX_VALUE.
final Segment<K,V>[] segments = this.segments;
long sum = 0;
long check = 0;
int[] mc = new int[segments.length];
// Try a few times to get accurate count. On failure due to
// continuous async changes in table, resort to locking.
for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
check = 0;
sum = 0;
int mcsum = 0;
for (int i = 0; i < segments.length; ++i) {
sum += segments[i].count;
mcsum += mc[i] = segments[i].modCount;
}
if (mcsum != 0) {
for (int i = 0; i < segments.length; ++i) {
check += segments[i].count;
if (mc[i] != segments[i].modCount) {
check = -1; // force retry
break;
}
}
}
if (check == sum)
break;
}
if (check != sum) { // Resort to locking all segments
sum = 0;
for (int i = 0; i < segments.length; ++i)
segments[i].lock();
for (int i = 0; i < segments.length; ++i)
sum += segments[i].count;
for (int i = 0; i < segments.length; ++i)
segments[i].unlock();
}
if (sum > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
else
return (int)sum;
| public java.util.Collection | values()Returns a {@link Collection} view of the values contained in this map.
The collection is backed by the map, so changes to the map are
reflected in the collection, and vice-versa. The collection
supports element removal, which removes the corresponding
mapping from this map, via the Iterator.remove,
Collection.remove, removeAll,
retainAll, and clear operations. It does not
support the add or addAll operations.
The view's iterator is a "weakly consistent" iterator
that will never throw {@link ConcurrentModificationException},
and guarantees to traverse elements as they existed upon
construction of the iterator, and may (but is not guaranteed to)
reflect any modifications subsequent to construction.
Collection<V> vs = values;
return (vs != null) ? vs : (values = new Values());
| private void | writeObject(java.io.ObjectOutputStream s)Save the state of the ConcurrentHashMap instance to a
stream (i.e., serialize it).
s.defaultWriteObject();
for (int k = 0; k < segments.length; ++k) {
Segment<K,V> seg = segments[k];
seg.lock();
try {
HashEntry<K,V>[] tab = seg.table;
for (int i = 0; i < tab.length; ++i) {
for (HashEntry<K,V> e = tab[i]; e != null; e = e.next) {
s.writeObject(e.key);
s.writeObject(e.value);
}
}
} finally {
seg.unlock();
}
}
s.writeObject(null);
s.writeObject(null);
|
|