Top Description Inners Fields Constructors Methods
org.codehaus.groovy.runtime.metaclass

public Class ConcurrentReaderHashMap

extends AbstractMap
implements Cloneable, Serializable
Class Inheritance
All Implemented Interfaces
java.io.Serializable, java.lang.Cloneable
Imports
java.io.IOException, .Serializable, java.util.AbstractCollection, .AbstractMap, .AbstractSet, .ArrayList, .Collection, .Enumeration, .Iterator, .Map, .NoSuchElementException, .Set

A hash table that supports mostly-concurrent reading, but exclusive writing. Because reads are not limited to periods without writes, a concurrent reader policy is weaker than a classic reader/writer policy, but is generally faster and allows more concurrency. This class is a good choice especially for tables that are mainly created by one thread during the start-up phase of a program, and from then on, are mainly read (with perhaps occasional additions or removals) in many threads. If you also need concurrency among writes, consider instead using ConcurrentHashMap.

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.

[ Introduction to this package. ]

Authors
Adapted from ConcurrentHashMap (Doug Lea), adapted by the Groovy community

Nested and Inner Type Summary

Modifier and TypeClass 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

Field Summary

Modifier and TypeField and Description
protected final ConcurrentReaderHashMap.BarrierLock
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<E>
protected transient Set<E>
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.Entry[]
table

The hash table data.

protected int
threshold

The table is rehashed when its size exceeds this threshold.

protected transient Collection<E>

Constructor Summary

AccessConstructor 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
ConcurrentReaderHashMap(Map<K, V> t)

Constructs a new map with the same mappings as the given map.

Method Summary

Modifier and TypeMethod and Description
public synchronized int

Returns:

the number of slots in this table
capacity
()

public synchronized void
clear()

Overrides java.util.AbstractMap.clear.

Implements java.util.Map.clear.

Removes all mappings from this map.
public synchronized Object

Returns:

a shallow copy of this map.
clone
()

Overrides java.util.AbstractMap.clone.

Returns a shallow copy of this ConcurrentReaderHashMap instance: the keys and values themselves are not cloned.
public boolean

Returns:

true if and only if some key maps to the value argument in this table as determined by the equals method; false otherwise.
contains
(Object
a value to search for.
value
)

Tests if some key maps into the specified value in this table.

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.
containsKey
(Object
possible key.
key
)

Overrides java.util.AbstractMap.containsKey.

Implements java.util.Map.containsKey.

Tests if the specified object is a key in this table.
public boolean

Returns:

true if this map maps one or more keys to the specified value.
containsValue
(Object
value whose presence in this map is to be tested.
value
)

Overrides java.util.AbstractMap.containsValue.

Implements java.util.Map.containsValue.

Returns true if this map maps one or more keys to the specified value.
public Enumeration<E>

Returns:

an enumeration of the values in this table.
elements
()

Returns an enumeration of the values in this table.

public Set<E>

Returns:

a collection view of the mappings contained in this map.
entrySet
()

Implements abstract java.util.AbstractMap.entrySet.

Implements java.util.Map.entrySet.

Returns a collection view of the mappings contained in this map.
protected boolean
eq(Object x, Object y)

Hides java.util.AbstractMap.eq.

Check for equality of non-null references x and y.
protected synchronized boolean
findAndRemoveEntry(Map.Entry<K, V> entry)

Helper method for entrySet.remove

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.
get
(Object
a key in the table.
key
)

Overrides java.util.AbstractMap.get.

Implements java.util.Map.get.

Returns the value to which the specified key is mapped in this table.
protected final 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 barrierLock

private static int
hash(Object x)

Return hash code for Object x.

public synchronized boolean

Returns:

true if this map contains no key-value mappings.
isEmpty
()

Overrides java.util.AbstractMap.isEmpty.

Implements java.util.Map.isEmpty.

Returns true if this map contains no key-value mappings.
public Enumeration<E>

Returns:

an enumeration of the keys in this table.
keys
()

Returns an enumeration of the keys in this table.

public Set<E>

Returns:

a set view of the keys contained in this map.
keySet
()

Overrides java.util.AbstractMap.keySet.

Implements java.util.Map.keySet.

Returns a set view of the keys contained in this map.
public float

Returns:

the load factor
loadFactor
()

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, or null if it did not have one.
put
(Object
the table key.
key
,
Object
the value.
value
)

Overrides java.util.AbstractMap.put.

Implements java.util.Map.put.

Maps the specified 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.util.AbstractMap.putAll.

Implements java.util.Map.putAll.

Copies all of the mappings from the specified map to this one.
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
rehash()

Rehashes the contents of this map into a new table with a larger capacity.

public Object

Returns:

the value to which the key had been mapped in this table, or null if the key did not have a mapping.
remove
(Object
the key that needs to be removed.
key
)

Overrides java.util.AbstractMap.remove.

Implements java.util.Map.remove.

Removes the key (and its corresponding value) from this table.
public synchronized int

Returns:

the number of key-value mappings in this map.
size
()

Overrides java.util.AbstractMap.size.

Implements java.util.Map.size.

Returns the number of key-value mappings in this map.
protected Object
sput(Object key, Object value, int hash)

Continuation of put(), called only when sync lock is held and interference has been detected.

protected Object
sremove(Object key, int hash)

Continuation of remove(), called only when sync lock is held and interference has been detected.

public Collection<E>

Returns:

a collection view of the values contained in this map.
values
()

Overrides java.util.AbstractMap.values.

Implements java.util.Map.values.

Returns a collection view of the values contained in this map.
private synchronized void
writeObject(ObjectOutputStream
the stream
s
)

Save the state of the ConcurrentReaderHashMap instance to a stream (i.e., serialize it).

Inherited from java.util.AbstractMap:
equalshashCodetoString