FileDocCategorySizeDatePackage
ConcurrentHashMap.javaAPI DocAndroid 1.5 API48938Wed May 06 22:41:02 BST 2009java.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.

This class implements 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.

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 int
DEFAULT_INITIAL_CAPACITY
The default initial number of table slots for this table. Used when not otherwise specified in 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 indexible using ints.
static final float
DEFAULT_LOAD_FACTOR
The default load factor for this table. Used when not otherwise specified in constructor.
static final int
DEFAULT_SEGMENTS
The default number of concurrency control segments.
static final int
MAX_SEGMENTS
The maximum number of segments to allow; used to bound constructor arguments.
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 and the specified load factor.

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

param
initialCapacity 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_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.

param
t the map

        this(Math.max((int) (t.size() / DEFAULT_LOAD_FACTOR) + 1,
                      11),
             DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
        putAll(t);
    
Methods Summary
public voidclear()
Removes all 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 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 key is null.

        int hash = hash(key); // throws NullPointerException if key null
        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 value is null.

        if (value == null)
            throw new NullPointerException();

        final Segment[] segments = this.segments;
        int[] mc = new int[segments.length];
        for (;;) {
            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;
        }
    
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 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 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.

return
a collection view of the mappings contained in this map.

        Set<Map.Entry<K,V>> es = entrySet;
        return (es != null) ? es : (entrySet = (Set<Map.Entry<K,V>>) (Set) new EntrySet());
    
public Vget(java.lang.Object key)
Returns the value to which the specified key is mapped in this table.

param
key a key in the table.
return
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 is null.

        int hash = hash(key); // throws NullPointerException if key null
        return segmentFor(hash).get(key, hash);
    
static inthash(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.

param
x the object serving as a key
return
the hash code


    /* ---------------- Small Utilities -------------- */

                                         
        
        int h = x.hashCode();
        h += ~(h << 9);
        h ^=  (h >>> 14);
        h +=  (h << 4);
        h ^=  (h >>> 10);
        return h;
    
public booleanisEmpty()

        final Segment[] segments = this.segments;
        /*
         * We need to 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 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 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.

return
a set view of the keys contained in this map.

        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 the table key.
param
value the value.
return
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 is null.

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

param
t Mappings to be stored in this 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 VputIfAbsent(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.

param
key key with which the specified value is to be associated.
param
value value to be associated with the specified key.
return
previous value associated with specified key, or null if there was no mapping for key. A null return can also indicate that the map previously associated null with the specified key, if the implementation supports null values.
throws
UnsupportedOperationException if the put operation is not supported by this map.
throws
ClassCastException if the class of the specified key or value prevents it from being stored in this map.
throws
NullPointerException if the specified key or value is null.

        if (value == null)
            throw new NullPointerException();
        int hash = hash(key);
        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 table. This method does nothing if the key is not in the table.

param
key the key that needs to be removed.
return
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 is null.

        int hash = hash(key);
        return segmentFor(hash).remove(key, hash, null);
    
public booleanremove(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.

param
key key with which the specified value is associated.
param
value value associated with the specified key.
return
true if the value was removed
throws
NullPointerException if the specified key is null.

        int hash = hash(key);
        return segmentFor(hash).remove(key, hash, value) != null;
    
public booleanreplace(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.

param
key key with which the specified value is associated.
param
oldValue value expected to be associated with the specified key.
param
newValue value to be associated with the specified key.
return
true if the value was replaced
throws
NullPointerException if the specified key or values are null.

        if (oldValue == null || newValue == null)
            throw new NullPointerException();
        int hash = hash(key);
        return segmentFor(hash).replace(key, hash, oldValue, newValue);
    
public Vreplace(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.

param
key key with which the specified value is associated.
param
value value to be associated with the specified key.
return
previous value associated with specified 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);
        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 (Segment<K,V>) segments[(hash >>> segmentShift) & segmentMask];
    
public intsize()

        final Segment[] segments = this.segments;
        int[] mc = new int[segments.length];
        for (;;) {
            long sum = 0;
            int mcsum = 0;
            for (int i = 0; i < segments.length; ++i) {
                sum += segments[i].count;
                mcsum += mc[i] = segments[i].modCount;
            }
            int check = 0;
            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) {
                if (sum > Integer.MAX_VALUE)
                    return Integer.MAX_VALUE;
                else
                    return (int)sum;
            }
        }
    
public java.util.Collectionvalues()
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 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.

return
a collection view of the values contained in this map.

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