FileDocCategorySizeDatePackage
ConcurrentHashMap.javaAPI DocJava SE 6 API47001Tue Jun 10 00:25:56 BST 2008java.util.concurrent

ConcurrentHashMap

public class ConcurrentHashMap extends AbstractMap implements Serializable, ConcurrentMap
A 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.

since
1.5
author
Doug Lea
param
the type of keys maintained by this map
param
the type of mapped values

Fields Summary
private static final long
serialVersionUID
static final int
DEFAULT_INITIAL_CAPACITY
The default initial capacity for this table, used when not otherwise specified in a constructor.
static final float
DEFAULT_LOAD_FACTOR
The default load factor for this table, used when not otherwise specified in a constructor.
static final int
DEFAULT_CONCURRENCY_LEVEL
The default concurrency level for this table, used when not otherwise specified in a constructor.
static final int
MAXIMUM_CAPACITY
The 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_SEGMENTS
The maximum number of segments to allow; used to bound constructor arguments.
static final int
RETRIES_BEFORE_LOCK
Number 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
segmentMask
Mask value for indexing into segments. The upper bits of a key's hash code are used to choose the segment.
final int
segmentShift
Shift value for indexing within segments.
final Segment[]
segments
The 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.

param
initialCapacity the initial capacity. The implementation performs internal sizing to accommodate this many elements.
param
loadFactor the load factor threshold, used to control resizing. Resizing may be performed when the average number of elements per bin exceeds this threshold.
param
concurrencyLevel the estimated number of concurrently updating threads. The implementation performs internal sizing to try to accommodate this many threads.
throws
IllegalArgumentException if the initial capacity is negative or the load factor or concurrencyLevel are nonpositive.

        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).

param
initialCapacity The implementation performs internal sizing to accommodate this many elements.
param
loadFactor the load factor threshold, used to control resizing. Resizing may be performed when the average number of elements per bin exceeds this threshold.
throws
IllegalArgumentException if the initial capacity of elements is negative or the load factor is nonpositive
since
1.6

        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).

param
initialCapacity the initial capacity. The implementation performs internal sizing to accommodate this many elements.
throws
IllegalArgumentException if the initial capacity of elements is negative.

        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).

param
m the map

        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY),
             DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
        putAll(m);
    
Methods Summary
public voidclear()
Removes all of the mappings from this map.

        for (int i = 0; i < segments.length; ++i)
            segments[i].clear();
    
public booleancontains(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.

param
value a value to search for
return
true if and only if some key maps to the value argument in this table as determined by the equals method; false otherwise
throws
NullPointerException if the specified value is null

        return containsValue(value);
    
public booleancontainsKey(java.lang.Object key)
Tests if the specified object is a key in this table.

param
key possible key
return
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 specified key is null

        int hash = hash(key.hashCode());
        return segmentFor(hash).containsKey(key, hash);
    
public booleancontainsValue(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.

param
value value whose presence in this map is to be tested
return
true if this map maps one or more keys to the specified value
throws
NullPointerException if the specified value is null

        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.Enumerationelements()
Returns an enumeration of the values in this table.

return
an enumeration of the values in this table
see
#values()

        return new ValueIterator();
    
public java.util.SetentrySet()
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 Vget(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.)

throws
NullPointerException if the specified key is null

        int hash = hash(key.hashCode());
        return segmentFor(hash).get(key, hash);
    
private static inthash(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 booleanisEmpty()
Returns true if this map contains no key-value mappings.

return
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.SetkeySet()
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.Enumerationkeys()
Returns an enumeration of the keys in this table.

return
an enumeration of the keys in this table
see
#keySet()

        return new KeyIterator();
    
public Vput(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.

param
key key with which the specified value is to be associated
param
value value to be associated with the specified key
return
the previous value associated with key, or null if there was no mapping for key
throws
NullPointerException if the specified key or value is null

        if (value == null)
            throw new NullPointerException();
        int hash = hash(key.hashCode());
        return segmentFor(hash).put(key, hash, value, false);
    
public voidputAll(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.

param
m mappings to be stored in this map

        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
            put(e.getKey(), e.getValue());
    
public VputIfAbsent(K key, V value)
{@inheritDoc}

return
the previous value associated with the specified key, or null if there was no mapping for the key
throws
NullPointerException if the specified key or value is null

        if (value == null)
            throw new NullPointerException();
        int hash = hash(key.hashCode());
        return segmentFor(hash).put(key, hash, value, true);
    
private voidreadObject(java.io.ObjectInputStream s)
Reconstitute the ConcurrentHashMap instance from a stream (i.e., deserialize it).

param
s the stream

        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 Vremove(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.

param
key the key that needs to be removed
return
the previous value associated with key, or null if there was no mapping for key
throws
NullPointerException if the specified key is null

	int hash = hash(key.hashCode());
        return segmentFor(hash).remove(key, hash, null);
    
public booleanremove(java.lang.Object key, java.lang.Object value)
{@inheritDoc}

throws
NullPointerException if the specified key is null

        int hash = hash(key.hashCode());
        if (value == null)
            return false;
        return segmentFor(hash).remove(key, hash, value) != null;
    
public booleanreplace(K key, V oldValue, V newValue)
{@inheritDoc}

throws
NullPointerException if any of the arguments are null

        if (oldValue == null || newValue == null)
            throw new NullPointerException();
        int hash = hash(key.hashCode());
        return segmentFor(hash).replace(key, hash, oldValue, newValue);
    
public Vreplace(K key, V value)
{@inheritDoc}

return
the previous value associated with the specified key, or null if there was no mapping for the key
throws
NullPointerException if the specified key or value is null

        if (value == null)
            throw new NullPointerException();
        int hash = hash(key.hashCode());
        return segmentFor(hash).replace(key, hash, value);
    
final java.util.concurrent.ConcurrentHashMap$SegmentsegmentFor(int hash)
Returns the segment that should be used for key with given hash

param
hash the hash code for the key
return
the segment

        return segments[(hash >>> segmentShift) & segmentMask];
    
public intsize()
Returns the number of key-value mappings in this map. If the map contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

return
the number of key-value mappings in this map

        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.Collectionvalues()
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 voidwriteObject(java.io.ObjectOutputStream s)
Save the state of the ConcurrentHashMap instance to a stream (i.e., serialize it).

param
s the stream
serialData
the key (Object) and value (Object) for each key-value mapping, followed by a null pair. The key-value mappings are emitted in no particular order.

        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);