Groovy Documentation

org.codehaus.groovy.runtime.metaclass
[Java] Class ConcurrentReaderHashMap

java.lang.Object
  java.util.AbstractMap
      org.codehaus.groovy.runtime.metaclass.ConcurrentReaderHashMap
All Implemented Interfaces:
java.util.Map, java.lang.Cloneable, java.io.Serializable

public class ConcurrentReaderHashMap
extends java.util.AbstractMap

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 Class Summary
protected static class ConcurrentReaderHashMap.BarrierLock

A Serializable class for barrier lock *

protected static class ConcurrentReaderHashMap.Entry

protected class ConcurrentReaderHashMap.HashIterator

protected class ConcurrentReaderHashMap.KeyIterator

protected class ConcurrentReaderHashMap.ValueIterator

 
Field Summary
static int DEFAULT_INITIAL_CAPACITY

The default initial number of table slots for this table (32).

static float DEFAULT_LOAD_FACTOR

The default load factor for this table (1.0).

protected ConcurrentReaderHashMap.BarrierLock barrierLock

Lock used only for its memory effects.

protected int count

The total number of mappings in the hash table.

protected java.util.Set entrySet

protected java.util.Set keySet

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

protected java.lang.Object lastWrite

field written to only to guarantee lock ordering.

protected float loadFactor

The load factor for the hash table.

protected ConcurrentReaderHashMap.Entry[] table

The hash table data.

protected int threshold

The table is rehashed when its size exceeds this threshold.

protected java.util.Collection values

 
Method Summary
java.lang.Object ConcurrentReaderHashMap(int initialCapacity, float loadFactor)

Constructs a new, empty map with the specified initial capacity and the specified load factor.

java.lang.Object ConcurrentReaderHashMap(int initialCapacity)

Constructs a new, empty map with the specified initial capacity and default load factor.

java.lang.Object ConcurrentReaderHashMap()

Constructs a new, empty map with a default initial capacity and load factor.

java.lang.Object ConcurrentReaderHashMap(java.util.Map t)

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

int capacity()

void clear()

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

java.lang.Object clone()

boolean contains(java.lang.Object value)

Copies all of the mappings from the specified map to this one.

boolean containsKey(java.lang.Object key)

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

boolean containsValue(java.lang.Object value)

Returns true if this map maps one or more keys to the specified value.

java.util.Enumeration elements()

java.util.Set entrySet()

protected boolean eq(java.lang.Object x, java.lang.Object y)

Check for equality of non-null references x and y.

protected boolean findAndRemoveEntry(java.util.Map$Entry entry)

java.lang.Object get(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 barrierLock

boolean isEmpty()

Returns true if this map contains no key-value mappings.

java.util.Set keySet()

java.util.Enumeration keys()

ConcurrentReaderHashMap collision list entry.

float loadFactor()

java.lang.Object put(java.lang.Object key, java.lang.Object value)

void putAll(java.util.Map t)

protected void recordModification(java.lang.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.

java.lang.Object remove(java.lang.Object key)

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

int size()

Returns the number of key-value mappings in this map.

protected java.lang.Object sput(java.lang.Object key, java.lang.Object value, int hash)

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

protected java.lang.Object sremove(java.lang.Object key, int hash)

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

java.util.Collection values()

 
Methods inherited from class java.util.AbstractMap
java.util.AbstractMap#remove(java.lang.Object), java.util.AbstractMap#get(java.lang.Object), java.util.AbstractMap#put(java.lang.Object, java.lang.Object), java.util.AbstractMap#equals(java.lang.Object), java.util.AbstractMap#toString(), java.util.AbstractMap#values(), java.util.AbstractMap#hashCode(), java.util.AbstractMap#clear(), java.util.AbstractMap#isEmpty(), java.util.AbstractMap#size(), java.util.AbstractMap#entrySet(), java.util.AbstractMap#putAll(java.util.Map), java.util.AbstractMap#keySet(), java.util.AbstractMap#containsKey(java.lang.Object), java.util.AbstractMap#containsValue(java.lang.Object), java.util.AbstractMap#wait(long, int), java.util.AbstractMap#wait(long), java.util.AbstractMap#wait(), java.util.AbstractMap#getClass(), java.util.AbstractMap#notify(), java.util.AbstractMap#notifyAll()
 
Methods inherited from class java.lang.Object
java.lang.Object#wait(long, int), java.lang.Object#wait(long), java.lang.Object#wait(), java.lang.Object#equals(java.lang.Object), java.lang.Object#toString(), java.lang.Object#hashCode(), java.lang.Object#getClass(), java.lang.Object#notify(), java.lang.Object#notifyAll()
 

Field Detail

DEFAULT_INITIAL_CAPACITY

public static final int DEFAULT_INITIAL_CAPACITY
The default initial number of table slots for this table (32). Used when not otherwise specified in constructor.


DEFAULT_LOAD_FACTOR

public static final float DEFAULT_LOAD_FACTOR
The default load factor for this table (1.0). Used when not otherwise specified in constructor.


barrierLock

protected final ConcurrentReaderHashMap.BarrierLock barrierLock
Lock used only for its memory effects.


count

protected int count
The total number of mappings in the hash table.


entrySet

protected java.util.Set entrySet


keySet

protected 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.
Returns:
a set view of the keys contained in this map.


lastWrite

protected java.lang.Object lastWrite
field written to only to guarantee lock ordering.


loadFactor

protected float loadFactor
The load factor for the hash table.
serial:


table

protected ConcurrentReaderHashMap.Entry[] table
The hash table data.


threshold

protected int threshold
The table is rehashed when its size exceeds this threshold. (The value of this field is always (int)(capacity * loadFactor).)
serial:


values

protected java.util.Collection values


 
Method Detail

ConcurrentReaderHashMap

public java.lang.Object ConcurrentReaderHashMap(int initialCapacity, float loadFactor)
Constructs a new, empty map with the specified initial capacity and the specified load factor.
throws:
IllegalArgumentException if the initial maximum number of elements is less than zero, or if the load factor is non-positive.
Parameters:
initialCapacity - the initial capacity The actual initial capacity is rounded to the nearest power of two.
loadFactor - the load factor of the ConcurrentReaderHashMap


ConcurrentReaderHashMap

public java.lang.Object ConcurrentReaderHashMap(int initialCapacity)
Constructs a new, empty map with the specified initial capacity and default load factor.
throws:
IllegalArgumentException if the initial maximum number of elements is less than zero.
Parameters:
initialCapacity - the initial capacity of the ConcurrentReaderHashMap.


ConcurrentReaderHashMap

public java.lang.Object ConcurrentReaderHashMap()
Constructs a new, empty map with a default initial capacity and load factor.


ConcurrentReaderHashMap

public java.lang.Object 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.


capacity

public int capacity()


clear

public void clear()
Returns a shallow copy of this ConcurrentReaderHashMap instance: the keys and values themselves are not cloned.
Returns:
a shallow copy of this map.


clone

public java.lang.Object clone()


contains

public boolean contains(java.lang.Object value)
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.
Parameters:
t - Mappings to be stored in this map.


containsKey

public boolean containsKey(java.lang.Object key)
Tests if the specified object is a key in this table.
Throws:
NullPointerException if the key is null.
Parameters:
key - possible key.
Returns:
true if and only if the specified object is a key in this table, as determined by the equals method; false otherwise.
See Also:
contains(Object)


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.
Throws:
NullPointerException if the value is null.
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.


elements

public java.util.Enumeration elements()


entrySet

public java.util.Set entrySet()


eq

protected boolean eq(java.lang.Object x, java.lang.Object y)
Check for equality of non-null references x and y.


findAndRemoveEntry

protected boolean findAndRemoveEntry(java.util.Map$Entry entry)


get

public java.lang.Object get(java.lang.Object key)
Returns the value to which the specified key is mapped in this table.
Throws:
NullPointerException if the key is null.
Parameters:
key - a key in the table.
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.
See Also:
put(Object, Object)


getTableForReading

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


isEmpty

public boolean isEmpty()
Returns true if this map contains no key-value mappings.
Returns:
true if this map contains no key-value mappings.


keySet

public java.util.Set keySet()


keys

public java.util.Enumeration keys()
ConcurrentReaderHashMap collision list entry.


loadFactor

public float loadFactor()


put

public java.lang.Object put(java.lang.Object key, java.lang.Object value)


putAll

public void putAll(java.util.Map t)


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 synch lock.


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.
Throws:
NullPointerException if the key is null.
Parameters:
key - the key that needs to be removed.
Returns:
the value to which the key had been mapped in this table, or null if the key did not have a mapping.


size

public int size()
Returns the number of key-value mappings in this map.
Returns:
the number of key-value mappings in this map.


sput

protected java.lang.Object sput(java.lang.Object key, java.lang.Object value, int hash)
Continuation of put(), called only when synch lock is held and interference has been detected.


sremove

protected java.lang.Object sremove(java.lang.Object key, int hash)
Continuation of remove(), called only when synch lock is held and interference has been detected.


values

public java.util.Collection values()


 

Groovy Documentation