Class ConcurrentReaderHashMap
- All Implemented Interfaces:
java.io.Serializable,java.lang.Cloneable,java.util.Map
public class ConcurrentReaderHashMap
extends java.util.AbstractMap
implements java.lang.Cloneable, java.io.Serializable
Successful retrievals using get(key) and containsKey(key) usually run without locking. Unsuccessful ones (i.e., when the key is not present) do involve brief synchronization (locking). Also, the size and isEmpty methods are always synchronized.
Because retrieval operations can ordinarily overlap with writing 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. In those rare contexts in which you use a hash table to synchronize operations across threads (for example, to prevent reads until after clears), you should either encase operations in synchronized blocks, or instead use java.util.Hashtable.
This class also supports optional guaranteed
exclusive reads, simply by surrounding a call within a synchronized
block, as in
ConcurrentReaderHashMap t; ... Object v;
synchronized(t) { v = t.get(k); }
But this is not usually necessary in practice. For
example, it is generally inefficient to write:
ConcurrentReaderHashMap t; ... // Inefficient version
Object key; ...
Object value; ...
synchronized(t) {
if (!t.containsKey(key))
t.put(key, value);
// other code if not previously present
}
else {
// other code if it was previously present
}
}
Instead, if the values are intended to be the same in each case, just take advantage of the fact that put returns
null if the key was not previously present:
ConcurrentReaderHashMap t; ... // Use this instead
Object key; ...
Object value; ...
Object oldValue = t.put(key, value);
if (oldValue == null) {
// other code if not previously present
}
else {
// other code if it was previously present
}
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. Sharing an iterator across multiple threads may lead to unpredictable results if the table is being concurrently modified. Again, you can ensure interference-free iteration by enclosing the iteration in a synchronized block.
This class may be used as a direct replacement for any use of java.util.Hashtable that does not depend on readers being blocked during updates. Like Hashtable but unlike java.util.HashMap, this class does NOT allow null to be used as a key or value. This class is also typically faster than ConcurrentHashMap when there is usually only one thread updating the table, but possibly many retrieving values from it.
Implementation note: A slightly faster implementation of this class will be possible once planned Java Memory Model revisions are in place.
- See Also:
- Serialized Form
-
Nested Class Summary
Nested Classes Modifier and Type Class Description protected static classConcurrentReaderHashMap.BarrierLockA Serializable class for barrier lockprotected static classConcurrentReaderHashMap.EntryConcurrentReaderHashMap collision list entry.protected classConcurrentReaderHashMap.HashIteratorprotected classConcurrentReaderHashMap.KeyIteratorprotected classConcurrentReaderHashMap.ValueIteratorNested classes/interfaces inherited from class java.util.AbstractMap
java.util.AbstractMap.SimpleEntry<K extends java.lang.Object,V extends java.lang.Object>, java.util.AbstractMap.SimpleImmutableEntry<K extends java.lang.Object,V extends java.lang.Object> -
Field Summary
Fields Modifier and Type Field Description protected ConcurrentReaderHashMap.BarrierLockbarrierLockLock used only for its memory effects.protected intcountThe total number of mappings in the hash table.static intDEFAULT_INITIAL_CAPACITYThe default initial number of table slots for this table (32).static floatDEFAULT_LOAD_FACTORThe default load factor for this table (1.0).protected java.util.SetentrySetprotected java.util.SetkeySetprotected java.lang.ObjectlastWritefield written to only to guarantee lock ordering.protected floatloadFactorThe load factor for the hash table.protected ConcurrentReaderHashMap.Entry[]tableThe hash table data.protected intthresholdThe table is rehashed when its size exceeds this threshold.protected java.util.Collectionvalues -
Constructor Summary
Constructors Constructor Description ConcurrentReaderHashMap()Constructs a new, empty map with a default initial capacity and load factor.ConcurrentReaderHashMap(int initialCapacity)Constructs a new, empty map with the specified initial capacity and default load factor.ConcurrentReaderHashMap(int initialCapacity, float loadFactor)Constructs a new, empty map with the specified initial capacity and the specified load factor.ConcurrentReaderHashMap(java.util.Map t)Constructs a new map with the same mappings as the given map. -
Method Summary
Modifier and Type Method Description intcapacity()voidclear()Removes all mappings from this map.java.lang.Objectclone()Returns a shallow copy of this ConcurrentReaderHashMap instance: the keys and values themselves are not cloned.booleancontains(java.lang.Object value)Tests if some key maps into the specified value in this table.booleancontainsKey(java.lang.Object key)Tests if the specified object is a key in this table.booleancontainsValue(java.lang.Object value)Returns true if this map maps one or more keys to the specified value.java.util.Enumerationelements()Returns an enumeration of the values in this table.java.util.SetentrySet()Returns a collection view of the mappings contained in this map.protected booleaneq(java.lang.Object x, java.lang.Object y)Check for equality of non-null references x and y.protected booleanfindAndRemoveEntry(java.util.Map.Entry entry)Helper method for entrySet.removejava.lang.Objectget(java.lang.Object key)Returns the value to which the specified key is mapped in this table.protected ConcurrentReaderHashMap.Entry[]getTableForReading()Get ref to table; the reference and the cells it accesses will be at least as fresh as from last use of barrierLockbooleanisEmpty()Returns true if this map contains no key-value mappings.java.util.Enumerationkeys()Returns an enumeration of the keys in this table.java.util.SetkeySet()Returns a set view of the keys contained in this map.floatloadFactor()java.lang.Objectput(java.lang.Object key, java.lang.Object value)Maps the specifiedkeyto the specifiedvaluein this table.voidputAll(java.util.Map t)Copies all of the mappings from the specified map to this one.protected voidrecordModification(java.lang.Object x)Force a memory synchronization that will cause all readers to see table.protected voidrehash()Rehashes the contents of this map into a new table with a larger capacity.java.lang.Objectremove(java.lang.Object key)Removes the key (and its corresponding value) from this table.intsize()Returns the number of key-value mappings in this map.protected java.lang.Objectsput(java.lang.Object key, java.lang.Object value, int hash)Continuation of put(), called only when sync lock is held and interference has been detected.protected java.lang.Objectsremove(java.lang.Object key, int hash)Continuation of remove(), called only when sync lock is held and interference has been detected.java.util.Collectionvalues()Returns a collection view of the values contained in this map.Methods inherited from class java.util.AbstractMap
equals, hashCode, toStringMethods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, waitMethods inherited from interface java.util.Map
compute, computeIfAbsent, computeIfPresent, forEach, getOrDefault, merge, putIfAbsent, remove, replace, replace, replaceAll
-
Field Details
-
barrierLock
Lock used only for its memory effects. -
lastWrite
protected transient java.lang.Object lastWritefield written to only to guarantee lock ordering. -
DEFAULT_INITIAL_CAPACITY
public static final int DEFAULT_INITIAL_CAPACITYThe default initial number of table slots for this table (32). Used when not otherwise specified in constructor.- See Also:
- Constant Field Values
-
DEFAULT_LOAD_FACTOR
public static final float DEFAULT_LOAD_FACTORThe default load factor for this table (1.0). Used when not otherwise specified in constructor.- See Also:
- Constant Field Values
-
table
The hash table data. -
count
protected transient int countThe total number of mappings in the hash table. -
threshold
protected int thresholdThe table is rehashed when its size exceeds this threshold. (The value of this field is always (int)(capacity * loadFactor).) -
loadFactor
protected float loadFactorThe load factor for the hash table. -
keySet
protected transient java.util.Set keySet -
entrySet
protected transient java.util.Set entrySet -
values
protected transient java.util.Collection values
-
-
Constructor Details
-
ConcurrentReaderHashMap
public ConcurrentReaderHashMap(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 of the ConcurrentReaderHashMap- Throws:
java.lang.IllegalArgumentException- if the initial maximum number of elements is less than zero, or if the load factor is non-positive.
-
ConcurrentReaderHashMap
public ConcurrentReaderHashMap(int initialCapacity)Constructs a new, empty map with the specified initial capacity and default load factor.- Parameters:
initialCapacity- the initial capacity of the ConcurrentReaderHashMap.- Throws:
java.lang.IllegalArgumentException- if the initial maximum number of elements is less than zero.
-
ConcurrentReaderHashMap
public ConcurrentReaderHashMap()Constructs a new, empty map with a default initial capacity and load factor. -
ConcurrentReaderHashMap
public ConcurrentReaderHashMap(java.util.Map t)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 16 (whichever is greater), and a default load factor.
-
-
Method Details
-
recordModification
protected final void recordModification(java.lang.Object x)Force a memory synchronization that will cause all readers to see table. Call only when already holding main sync lock. -
getTableForReading
Get ref to table; the reference and the cells it accesses will be at least as fresh as from last use of barrierLock -
eq
protected boolean eq(java.lang.Object x, java.lang.Object y)Check for equality of non-null references x and y. -
size
public int size()Returns the number of key-value mappings in this map.- Specified by:
sizein interfacejava.util.Map- Overrides:
sizein classjava.util.AbstractMap- 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:
isEmptyin interfacejava.util.Map- Overrides:
isEmptyin classjava.util.AbstractMap- Returns:
- true if this map contains no key-value mappings.
-
get
public java.lang.Object get(java.lang.Object key)Returns the value to which the specified key is mapped in this table.- Specified by:
getin interfacejava.util.Map- Overrides:
getin classjava.util.AbstractMap- Parameters:
key- a key in the table.- Returns:
- the value to which the key is mapped in this table;
nullif the key is not mapped to any value in this table. - Throws:
java.lang.NullPointerException- if the key isnull.- See Also:
put(Object, Object)
-
containsKey
public boolean containsKey(java.lang.Object key)Tests if the specified object is a key in this table.- Specified by:
containsKeyin interfacejava.util.Map- Overrides:
containsKeyin classjava.util.AbstractMap- Parameters:
key- possible key.- Returns:
trueif and only if the specified object is a key in this table, as determined by the equals method;falseotherwise.- Throws:
java.lang.NullPointerException- if the key isnull.- See Also:
contains(Object)
-
put
public java.lang.Object put(java.lang.Object key, java.lang.Object value)Maps the specifiedkeyto the specifiedvaluein this table. Neither the key nor the value can benull.The value can be retrieved by calling the
getmethod with a key that is equal to the original key.- Specified by:
putin interfacejava.util.Map- Overrides:
putin classjava.util.AbstractMap- Parameters:
key- the table key.value- the value.- Returns:
- the previous value of the specified key in this table,
or
nullif it did not have one. - Throws:
java.lang.NullPointerException- if the key or value isnull.- See Also:
Object.equals(Object),get(Object)
-
sput
protected java.lang.Object sput(java.lang.Object key, java.lang.Object value, int hash)Continuation of put(), called only when sync lock is held and interference has been detected. -
rehash
protected void rehash()Rehashes the contents of this map into a new table with a larger capacity. This method is called automatically when the number of keys in this map exceeds its capacity and load factor. -
remove
public java.lang.Object 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.- Specified by:
removein interfacejava.util.Map- Overrides:
removein classjava.util.AbstractMap- Parameters:
key- the key that needs to be removed.- Returns:
- the value to which the key had been mapped in this table,
or
nullif the key did not have a mapping. - Throws:
java.lang.NullPointerException- if the key isnull.
-
sremove
protected java.lang.Object sremove(java.lang.Object key, int hash)Continuation of remove(), called only when sync lock is held and interference has been detected. -
containsValue
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.- Specified by:
containsValuein interfacejava.util.Map- Overrides:
containsValuein classjava.util.AbstractMap- 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:
java.lang.NullPointerException- if the value isnull.
-
contains
public boolean contains(java.lang.Object value)Tests if some key maps into the specified value in this table. This operation is more expensive than thecontainsKeymethod.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:
trueif and only if some key maps to thevalueargument in this table as determined by the equals method;falseotherwise.- Throws:
java.lang.NullPointerException- if the value isnull.- See Also:
containsKey(Object),containsValue(Object),Map
-
putAll
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.- Specified by:
putAllin interfacejava.util.Map- Overrides:
putAllin classjava.util.AbstractMap- Parameters:
t- Mappings to be stored in this map.
-
clear
public void clear()Removes all mappings from this map.- Specified by:
clearin interfacejava.util.Map- Overrides:
clearin classjava.util.AbstractMap
-
clone
public java.lang.Object clone()Returns a shallow copy of this ConcurrentReaderHashMap instance: the keys and values themselves are not cloned.- Overrides:
clonein classjava.util.AbstractMap- Returns:
- a shallow copy of this map.
-
keySet
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.- Specified by:
keySetin interfacejava.util.Map- Overrides:
keySetin classjava.util.AbstractMap- Returns:
- a set view of the keys contained in this map.
-
values
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.- Specified by:
valuesin interfacejava.util.Map- Overrides:
valuesin classjava.util.AbstractMap- Returns:
- a collection view of the values contained in this map.
-
entrySet
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.- Specified by:
entrySetin interfacejava.util.Map- Specified by:
entrySetin classjava.util.AbstractMap- Returns:
- a collection view of the mappings contained in this map.
-
findAndRemoveEntry
protected boolean findAndRemoveEntry(java.util.Map.Entry entry)Helper method for entrySet.remove -
keys
public java.util.Enumeration keys()Returns an enumeration of the keys in this table.- Returns:
- an enumeration of the keys in this table.
- See Also:
Enumeration,elements(),keySet(),Map
-
elements
public java.util.Enumeration elements()Returns an enumeration of the values in this table. Use the Enumeration methods on the returned object to fetch the elements sequentially. -
capacity
public int capacity()- Returns:
- the number of slots in this table
-
loadFactor
public float loadFactor()- Returns:
- the load factor
-