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 java.util.Hashtable} but unlike {@link
java.util.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 int | DEFAULT_INITIAL_CAPACITYThe default initial number of table slots for this table.
Used when not otherwise specified in 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 indexible
using ints. | static final float | DEFAULT_LOAD_FACTORThe default load factor for this table. Used when not
otherwise specified in constructor. | static final int | DEFAULT_SEGMENTSThe default number of concurrency control segments. | 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 = new Segment[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)Creates a new, empty map with the specified initial
capacity, and with default load factor and concurrencyLevel.
this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
| public ConcurrentHashMap()Creates a new, empty map with a default initial capacity,
load factor, and concurrencyLevel.
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
| public ConcurrentHashMap(Map t)Creates 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 11 (whichever is greater), and a default load factor
and concurrencyLevel.
this(Math.max((int) (t.size() / DEFAULT_LOAD_FACTOR) + 1,
11),
DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
putAll(t);
|
Methods Summary |
---|
public void | clear()Removes all 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); // throws NullPointerException if key null
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[] 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 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.
The view's returned iterator is a "weakly consistent" iterator that
will never throw {@link java.util.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 = (Set<Map.Entry<K,V>>) (Set) new EntrySet());
| public V | get(java.lang.Object key)Returns the value to which the specified key is mapped in this table.
int hash = hash(key); // throws NullPointerException if key null
return segmentFor(hash).get(key, hash);
| static int | hash(java.lang.Object x)Returns a hash code for non-null Object x.
Uses the same hash code spreader as most other java.util hash tables.
/* ---------------- Small Utilities -------------- */
int h = x.hashCode();
h += ~(h << 9);
h ^= (h >>> 14);
h += (h << 4);
h ^= (h >>> 10);
return h;
| public boolean | isEmpty()
final Segment[] 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 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 returned iterator is a "weakly consistent" iterator that
will never throw {@link java.util.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);
return segmentFor(hash).put(key, hash, value, false);
| public void | putAll(java.util.Map t)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 (Iterator<? extends Map.Entry<? extends K, ? extends V>> it = (Iterator<? extends Map.Entry<? extends K, ? extends V>>) t.entrySet().iterator(); it.hasNext(); ) {
Entry<? extends K, ? extends V> e = it.next();
put(e.getKey(), e.getValue());
}
| public V | putIfAbsent(K key, V value)If the specified key is not already associated
with a value, associate it with the given value.
This is equivalent to
if (!map.containsKey(key))
return map.put(key, value);
else
return map.get(key);
Except that the action is performed atomically.
if (value == null)
throw new NullPointerException();
int hash = hash(key);
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
table. This method does nothing if the key is not in the table.
int hash = hash(key);
return segmentFor(hash).remove(key, hash, null);
| public boolean | remove(java.lang.Object key, java.lang.Object value)Remove entry for key only if currently mapped to given value.
Acts as
if (map.get(key).equals(value)) {
map.remove(key);
return true;
} else return false;
except that the action is performed atomically.
int hash = hash(key);
return segmentFor(hash).remove(key, hash, value) != null;
| public boolean | replace(K key, V oldValue, V newValue)Replace entry for key only if currently mapped to given value.
Acts as
if (map.get(key).equals(oldValue)) {
map.put(key, newValue);
return true;
} else return false;
except that the action is performed atomically.
if (oldValue == null || newValue == null)
throw new NullPointerException();
int hash = hash(key);
return segmentFor(hash).replace(key, hash, oldValue, newValue);
| public V | replace(K key, V value)Replace entry for key only if currently mapped to some value.
Acts as
if ((map.containsKey(key)) {
return map.put(key, value);
} else return null;
except that the action is performed atomically.
if (value == null)
throw new NullPointerException();
int hash = hash(key);
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 (Segment<K,V>) segments[(hash >>> segmentShift) & segmentMask];
| public int | size()
final Segment[] 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 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 returned iterator is a "weakly consistent" iterator that
will never throw {@link java.util.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 = (Segment<K,V>)segments[k];
seg.lock();
try {
HashEntry[] tab = seg.table;
for (int i = 0; i < tab.length; ++i) {
for (HashEntry<K,V> e = (HashEntry<K,V>)tab[i]; e != null; e = e.next) {
s.writeObject(e.key);
s.writeObject(e.value);
}
}
} finally {
seg.unlock();
}
}
s.writeObject(null);
s.writeObject(null);
|
|