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.
| Modifier and Type | Class and Description |
|---|---|
| protected static class | ConcurrentReaderHashMap.BarrierLock
A Serializable class for barrier lock |
| protected static class | ConcurrentReaderHashMap.Entry
ConcurrentReaderHashMap collision list entry. |
| private class | |
| protected class | |
| protected class | |
| private class | |
| protected class | |
| private class |
| Modifier and Type | Field and Description |
|---|---|
| protected final ConcurrentReaderHashMap. | barrierLock
Lock used only for its memory effects. |
| protected transient int | count
The total number of mappings in the hash table. |
| public static final int | DEFAULT_INITIAL_CAPACITY
The default initial number of table slots for this table (32). |
| public static final float | DEFAULT_LOAD_FACTOR
The default load factor for this table (1.0). |
| protected transient Set | |
| protected transient Set | |
| protected transient Object | lastWrite
field written to only to guarantee lock ordering. |
| protected float | loadFactor
The load factor for the hash table. |
| private static final int | MAXIMUM_CAPACITY
The maximum capacity, used if a higher value is implicitly specified by either of the constructors with arguments. |
| private static final int | MINIMUM_CAPACITY
The minimum capacity, used if a lower value is implicitly specified by either of the constructors with arguments. |
| private static final long | |
| protected transient ConcurrentReaderHashMap. | table
The hash table data. |
| protected int | threshold
The table is rehashed when its size exceeds this threshold. |
| protected transient Collection |
| Access | Constructor and Description |
|---|---|
| public | ConcurrentReaderHashMap(int
the initial capacity
The actual initial capacity is rounded to the nearest power of two. initialCapacity, float the load factor of the ConcurrentReaderHashMap loadFactor)Constructs a new, empty map with the specified initial capacity and the specified load factor. |
| public | ConcurrentReaderHashMap(int
the initial capacity of the
ConcurrentReaderHashMap. initialCapacity)Constructs a new, empty map with the specified initial capacity and default load factor. |
| public | ConcurrentReaderHashMap()
Constructs a new, empty map with a default initial capacity and load factor. |
| public |
| Modifier and Type | Method and Description |
|---|---|
| public synchronized int | |
| public synchronized void | clear()
Overrides java. Implements java. |
| public synchronized Object | Returns: a shallow copy of this map.Overrides java. |
| public boolean | |
| public boolean | Returns: true if and only if the specified object
is a key in this table, as determined by the
equals method; false otherwise.possible key. key)Overrides java. Implements java. |
| public boolean | Returns: true if this map maps one or more keys to the specified value.value whose presence in this map is to be tested. value)Overrides java. Implements java. |
| public Enumeration | Returns: an enumeration of the values in this table.Returns an enumeration of the values in this table. |
| public Set | Returns: a collection view of the mappings contained in this map.Implements abstract java. Implements java. |
| protected boolean | eq(Object x, Object y)
Hides java. |
| protected synchronized boolean | |
| public Object | Returns: the value to which the key is mapped in this table;null if the key is not mapped to any value in
this table.a key in the table. key)Overrides java. Implements java. |
| protected final ConcurrentReaderHashMap. | getTableForReading()
Get ref to table; the reference and the cells it accesses will be at least as fresh as from last use of barrierLock |
| private static int | |
| public synchronized boolean | Returns: true if this map contains no key-value mappings.Overrides java. Implements java. |
| public Enumeration | Returns: an enumeration of the keys in this table.Returns an enumeration of the keys in this table. |
| public Set | Returns: a set view of the keys contained in this map.Overrides java. Implements java. |
| public float | |
| private static int | p2capacity(int initialCapacity)
Returns the appropriate capacity (power of two) for the specified initial capacity argument. |
| public Object | Returns: the previous value of the specified key in this table, ornull if it did not have one.the table key. key, Object the value. value)Overrides java. Implements java. key to the specified
value in this table.
|
| public synchronized void | putAll(Map<K, V>
Mappings to be stored in this map. t)Overrides java. Implements java. |
| private synchronized void | readObject(ObjectInputStream
the stream s)Reconstitute the ConcurrentReaderHashMap instance from a stream (i.e., deserialize it). |
| protected final void | recordModification(Object x)
Force a memory synchronization that will cause all readers to see table. |
| protected void | |
| public Object | Returns: the value to which the key had been mapped in this table, ornull if the key did not have a mapping.the key that needs to be removed. key)Overrides java. Implements java. |
| public synchronized int | Returns: the number of key-value mappings in this map.Overrides java. Implements java. |
| protected Object | |
| protected Object | |
| public Collection | Returns: a collection view of the values contained in this map.Overrides java. Implements java. |
| private synchronized void | writeObject(ObjectOutputStream
the stream s)Save the state of the ConcurrentReaderHashMap instance to a stream (i.e., serialize it). |