org.jomc.util
Class WeakIdentityHashMap

Package class diagram package WeakIdentityHashMap
java.lang.Object
  extended by org.jomc.util.WeakIdentityHashMap
All Implemented Interfaces:
Map

public final class WeakIdentityHashMap
extends Object
implements Map

Hash-table based Map implementation with weak keys, using object-identity in place of object-equality when comparing keys.

In a WeakIdentityHashMap two keys k1 and k2 are considered equal if and only if k1==k2 evaluates to true. An entry will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations and is not a general-purpose Map implementation! Although it implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects.

This class has performance characteristics similar to those of the HashMap class, and has the same efficiency parameters of initialCapacity and loadFactor. All of the optional map operations are provided. It does not support null values and the null key. All methods taking a key or value will throw a NullPointerException when given a null reference. No guarantees are made as to the order of the map; in particular, there is no guarantee that the order will remain constant over time. Like most collection classes, this class is not synchronized. A synchronized WeakIdentityHashMap may be constructed using the Collections.synchronizedMap method.

The behavior of the WeakIdentityHashMap class depends in part upon the actions of the garbage collector, so several Map invariants do not hold for this class. Because the garbage collector may discard keys at any time, a WeakIdentityHashMap may behave as though an unknown thread is silently removing entries. In particular, even if synchronizing on a WeakIdentityHashMap instance and invoking none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive examinations of the key set, the value collection, and the entry set to yield successively smaller numbers of elements. To protect against such situations all Iterators and Entrys created by this class throw an IllegalStateException when a key becomes null or a mapping got removed.

The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationExceptions on a best-effort basis. Therefore, it would be wrong to write a program that depends on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

Version:
$Id: WeakIdentityHashMap.java 509 2009-09-21 13:54:49Z schulte2005 $
Author:
Christian Schulte
See Also:
HashMap, WeakHashMap, IdentityHashMap, Collections.synchronizedMap(java.util.Map)

Nested Class Summary
private static class WeakIdentityHashMap.Entry
          A map entry (key-value pair) with weakly referenced key.
private  class WeakIdentityHashMap.EntryIterator
          An iterator over the hash-table backing the implementation.
 
Field Summary
private static int DEFAULT_INITIAL_CAPACITY
          Default initial capacity (2^4).
private static float DEFAULT_LOAD_FACTOR
          Default load factor (0.75).
private  Set entrySet
          The entry set view of the map.
private  WeakIdentityHashMap.Entry[] hashTable
          The hash-table backing the map.
private  int initialCapacity
          The initial capacity of the hash table.
private  Set keySet
          The key set view of the map.
private  float loadFactor
          The load factor for the hash table.
private static int MAXIMUM_CAPACITY
          Maximum capacity of the hash-table backing the implementation (2^30).
private  int modifications
          The number of times the map got structurally modified.
private  WeakIdentityHashMap.Entry NULL_ENTRY
          Null value returned by method getEntry(Object).
private  ReferenceQueue referenceQueue
          Queue, to which weak keys are appended to.
private  int resizeThreshold
          The size value at which the hash table needs resizing.
private  int size
          The number of mappings held by the map.
private  Collection valueCollection
          The value collection view of the map.
 
Constructor Summary
WeakIdentityHashMap()
          Constructs a new, empty WeakIdentityHashMap with the default initial capacity (16) and load factor (0.75).
WeakIdentityHashMap(float loadFactor)
          Constructs a new, empty WeakIdentityHashMap with the default initial capacity (16) and the given load factor.
WeakIdentityHashMap(int initialCapacity)
          Constructs a new, empty WeakIdentityHashMap with the given initial capacity and the default load factor (0.75).
WeakIdentityHashMap(int initialCapacity, float loadFactor)
          Constructs a new, empty WeakIdentityHashMap with the given initial capacity and the given load factor.
 
Method Summary
private  int calculateCapacity()
           
 void clear()
          Removes all of the mappings from this map so that the map will be empty after this call returns.
 boolean containsKey(Object key)
          Gets a flag indicating if this map contains a mapping for a given key.
 boolean containsValue(Object value)
          Gets a flag indicating if this map maps one or more keys to the specified value.
private  void decreaseSize()
           
 Set entrySet()
          Gets a Set view of the mappings contained in this map.
 boolean equals(Object o)
          Compares the specified object with this map for equality.
 Object get(Object key)
          Gets the value to which a given key is mapped, or null if this map contains no mapping for that key.
private  WeakIdentityHashMap.Entry getEntry(Object key)
           
private static int getHashCode(Object key)
          Gets a hash-code value for a given key.
private  WeakIdentityHashMap.Entry[] getHashTable()
          Gets the hash-table backing the instance.
private static int getHashTableIndex(int hashCode, int capacity)
          Gets the index of a hash code value.
 int hashCode()
          Gets the hash code value for this map.
private  void increaseSize()
           
private  String internalString()
          Creates a string representing the mappings of the instance.
 boolean isEmpty()
          Gets a flag indicating if this map is empty.
 Set keySet()
          Gets a Set view of the keys contained in this map.
private  void purge()
          Removes any garbage collected entries.
 Object put(Object key, Object value)
          Associates a given value with a given key in this map.
 void putAll(Map m)
          Copies all of the mappings from a given map to this map.
 Object remove(Object key)
          Removes the mapping for a given key from this map if it is present.
 int size()
          Gets the number of key-value mappings in this map.
 String toString()
          Returns a string representation of the object.
 Collection values()
          Gets a Collection view of the values contained in this map.
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

MAXIMUM_CAPACITY

private static final int MAXIMUM_CAPACITY
Maximum capacity of the hash-table backing the implementation (2^30).

See Also:
Constant Field Values

DEFAULT_INITIAL_CAPACITY

private static final int DEFAULT_INITIAL_CAPACITY
Default initial capacity (2^4).

See Also:
Constant Field Values

DEFAULT_LOAD_FACTOR

private static final float DEFAULT_LOAD_FACTOR
Default load factor (0.75).

See Also:
Constant Field Values

modifications

private volatile int modifications
The number of times the map got structurally modified.


size

private int size
The number of mappings held by the map.


resizeThreshold

private int resizeThreshold
The size value at which the hash table needs resizing.


hashTable

private WeakIdentityHashMap.Entry[] hashTable
The hash-table backing the map.


referenceQueue

private final ReferenceQueue referenceQueue
Queue, to which weak keys are appended to.


keySet

private transient Set keySet
The key set view of the map.


entrySet

private transient Set entrySet
The entry set view of the map.


valueCollection

private transient Collection valueCollection
The value collection view of the map.


initialCapacity

private final int initialCapacity
The initial capacity of the hash table.


loadFactor

private final float loadFactor
The load factor for the hash table.


NULL_ENTRY

private final WeakIdentityHashMap.Entry NULL_ENTRY
Null value returned by method getEntry(Object).

Constructor Detail

WeakIdentityHashMap

public WeakIdentityHashMap()
Constructs a new, empty WeakIdentityHashMap with the default initial capacity (16) and load factor (0.75).


WeakIdentityHashMap

public WeakIdentityHashMap(int initialCapacity)
Constructs a new, empty WeakIdentityHashMap with the given initial capacity and the default load factor (0.75).

Parameters:
initialCapacity - The initial capacity of the WeakIdentityHashMap.
Throws:
IllegalArgumentException - if initialCapacity is negative or greater than the maximum supported capacity (2^30).

WeakIdentityHashMap

public WeakIdentityHashMap(float loadFactor)
Constructs a new, empty WeakIdentityHashMap with the default initial capacity (16) and the given load factor.

Parameters:
loadFactor - The load factor of the WeakIdentityHashMap.
Throws:
IllegalArgumentException - if loadFactor is nonpositive.

WeakIdentityHashMap

public WeakIdentityHashMap(int initialCapacity,
                           float loadFactor)
Constructs a new, empty WeakIdentityHashMap with the given initial capacity and the given load factor.

Parameters:
initialCapacity - The initial capacity of the WeakIdentityHashMap.
loadFactor - The load factor of the WeakIdentityHashMap.
Throws:
IllegalArgumentException - if initialCapacity is negative or greater than the maximum supported capacity (2^30), or if loadFactor is nonpositive.
Method Detail

size

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

If the map contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

Specified by:
size in interface Map
Returns:
The number of key-value mappings in this map.

isEmpty

public boolean isEmpty()
Gets a flag indicating if this map is empty.

Specified by:
isEmpty in interface Map
Returns:
true if this map contains no key-value mappings; false if this map contains at least one mapping.

containsKey

public boolean containsKey(Object key)
Gets a flag indicating if this map contains a mapping for a given key.

More formally, returns true if and only if this map contains a mapping for a key k such that key==k. There can be at most one such mapping.

Specified by:
containsKey in interface Map
Parameters:
key - The key whose presence in this map is to be tested.
Returns:
true if this map contains a mapping for key; false if this map does not contain a mapping for key.
Throws:
NullPointerException - if key is null.

containsValue

public boolean containsValue(Object value)
Gets a flag indicating if this map maps one or more keys to the specified value.

More formally, this method returns true if and only if this map contains at least one mapping to a value v such that value.equals(v). This operation requires time linear in the map size.

Specified by:
containsValue in interface Map
Parameters:
value - The value whose presence in this map is to be tested.
Returns:
true if this map maps one or more keys to value; false if this map does not map any key to value.
Throws:
NullPointerException - if value is null.

get

public Object get(Object key)
Gets the value to which a given key is mapped, or null if this map contains no mapping for that key.

More formally, if this map contains a mapping from a key k to a value v such that key==k, then this method returns v; otherwise it returns null. There can be at most one such mapping.

Specified by:
get in interface Map
Parameters:
key - The key whose associated value is to be returned.
Returns:
the value to which key is mapped, or null if this map contains no mapping for key.
Throws:
NullPointerException - if key is null.

put

public Object put(Object key,
                  Object value)
Associates a given value with a given key in this map.

If the map previously contained a mapping for that key, the old value is replaced by the given value.

Specified by:
put in interface Map
Parameters:
key - The key with which value is to be associated.
value - The value to be associated with key.
Returns:
the value previously associated with key, or null if there was no mapping for key.
Throws:
NullPointerException - if key or value is null.

remove

public Object remove(Object key)
Removes the mapping for a given key from this map if it is present.

More formally, if this map contains a mapping from key k to value v such that key==k, that mapping is removed. The map can contain at most one such mapping. The map will not contain a mapping for the given key once the call returns.

Specified by:
remove in interface Map
Parameters:
key - The key whose mapping is to be removed from the map.
Returns:
the value previously associated with key, or null if there was no mapping for key.
Throws:
NullPointerException - if key is null.

putAll

public void putAll(Map m)
Copies all of the mappings from a given map to this map.

The effect of this call is equivalent to that of calling put(k, v) on this map once for each mapping from key k to value v in the given map. The behavior of this operation is undefined if the given map is modified while the operation is in progress.

Specified by:
putAll in interface Map
Parameters:
m - The mappings to be stored in this map.
Throws:
NullPointerException - if map is null, or if map contains null keys or values.

clear

public void clear()
Removes all of the mappings from this map so that the map will be empty after this call returns.

Specified by:
clear in interface Map

keySet

public Set keySet()
Gets 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. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined, that is, the iterator may throw an IllegalStateException. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

Specified by:
keySet in interface Map
Returns:
a set view of the keys contained in this map.

values

public Collection values()
Gets 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. If the map is modified while an iteration over the collection is in progress (except through the iterator's own remove operation), the results of the iteration are undefined, that is, the iterator may throw an IllegalStateException. 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:
values in interface Map
Returns:
a collection view of the values contained in this map.

entrySet

public Set entrySet()
Gets a Set view of the mappings contained in this map.

The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined, that is, the iterator may throw an IllegalStateException. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

Specified by:
entrySet in interface Map
Returns:
a set view of the mappings contained in this map.

toString

public String toString()
Returns a string representation of the object.

Overrides:
toString in class Object
Returns:
a string representation of the object.

equals

public boolean equals(Object o)
Compares the specified object with this map for equality.

Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()).

Specified by:
equals in interface Map
Overrides:
equals in class Object
Parameters:
o - The object to be compared for equality with this map.
Returns:
true if o is equal to this map; false if o is not equal to this map.

hashCode

public int hashCode()
Gets the hash code value for this map.

The hash code of a map is defined to be the sum of the hash codes of each entry in the map's entrySet() view.

Specified by:
hashCode in interface Map
Overrides:
hashCode in class Object
Returns:
the hash code value for this map.

internalString

private String internalString()
Creates a string representing the mappings of the instance.

Returns:
a string representing the mappings of the instance.

getHashCode

private static int getHashCode(Object key)
Gets a hash-code value for a given key.

Parameters:
key - The key to get a hash-code value for.
Returns:
Hash-code value of key.

getHashTableIndex

private static int getHashTableIndex(int hashCode,
                                     int capacity)
Gets the index of a hash code value.

Parameters:
hashCode - The hash code value to return the index of.
capacity - The capacity to return an index for.
Returns:
the index of hashCode for capacity.

getHashTable

private WeakIdentityHashMap.Entry[] getHashTable()
Gets the hash-table backing the instance.

This method creates a new hash-table and re-hashes any mappings whenever the size of the map gets greater than the capacity of the internal hash-table times the load factor value.

Returns:
the hash-table backing the instance.

purge

private void purge()
Removes any garbage collected entries.


increaseSize

private void increaseSize()

decreaseSize

private void decreaseSize()

calculateCapacity

private int calculateCapacity()

getEntry

private WeakIdentityHashMap.Entry getEntry(Object key)


Copyright © 2005-2009 The JOMC Project. All Rights Reserved.