Package extra166y

Class CustomConcurrentHashMap<K,V>

java.lang.Object
java.util.AbstractMap<K,V>
extra166y.CustomConcurrentHashMap<K,V>
Type Parameters:
K - the type of keys maintained by this map
V - the type of mapped values
All Implemented Interfaces:
Serializable, ConcurrentMap<K,V>, Map<K,V>

public class CustomConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable
A java.util.ConcurrentMap supporting user-defined equivalence comparisons, soft, weak, or strong keys and values, and user-supplied computational methods for setting and updating values. In particular: Per-map settings are established in constructors, as in the following usages (that assume static imports to simplify expression of configuration parameters):
 
 identityMap = new CustomConcurrentHashMap<Person,Salary>
     (STRONG, IDENTITY, STRONG, EQUALS, 0);
 weakKeyMap = new CustomConcurrentHashMap<Person,Salary>
     (WEAK, IDENTITY, STRONG, EQUALS, 0);
     .weakKeys());
 byNameMap = new CustomConcurrentHashMap<Person,Salary>
     (STRONG,
      new Equivalence<Person>() {
          public boolean equal(Person k, Object x) {
            return x instanceof Person && k.name.equals(((Person)x).name);
          }
          public int hash(Object x) {
             return (x instanceof Person) ? ((Person)x).name.hashCode() : 0;
          }
        },
      STRONG, EQUALS, 0);
 
 
The first usage above provides a replacement for IdentityHashMap, and the second a replacement for WeakHashMap, adding concurrency, asynchronous cleanup, and identity-based equality for keys. The third usage illustrates a map with a custom Equivalence that looks only at the name field of a (fictional) Person class.

This class also includes nested class CustomConcurrentHashMap.KeySet that provides space-efficient Set views of maps, also supporting method intern, which may be of use in canonicalizing elements.

When used with (Weak or Soft) Reference keys and/or values, elements that have asynchronously become null are treated as absent from the map and (eventually) removed from maps via a background thread common across all maps. Because of the potential for asynchronous clearing of References, methods such as containsValue have weaker guarantees than you might expect even in the absence of other explicitly concurrent operations. For example containsValue(value) may return true even if value is no longer available upon return from the method.

When Equivalences other than equality are used, the returned collections may violate the specifications of Map and/or Set interfaces, which mandate the use of the equals method when comparing objects. The methods of this class otherwise have properties similar to those of java.util.ConcurrentHashMap under its default settings. To adaptively maintain semantics and performance under varying conditions, this class does not support load factor or concurrency level parameters. This class does not permit null keys or values. This class is serializable; however, serializing a map that uses soft or weak references can give unpredictable results. This class supports all optional operations of the ConcurrentMap interface. It supports have weakly consistent iteration: an iterator over one of the map's view collections may reflect some, all or none of the changes made to the collection after the iterator was created.

This class is a member of the Java Collections Framework.

See Also:
  • Field Details

  • Constructor Details

    • CustomConcurrentHashMap

      public CustomConcurrentHashMap(CustomConcurrentHashMap.Strength keyStrength, CustomConcurrentHashMap.Equivalence<? super K> keyEquivalence, CustomConcurrentHashMap.Strength valueStrength, CustomConcurrentHashMap.Equivalence<? super V> valueEquivalence, int expectedSize)
      Creates a new CustomConcurrentHashMap with the given parameters
      Parameters:
      keyStrength - the strength for keys
      keyEquivalence - the Equivalence to use for keys
      valueStrength - the strength for values
      valueEquivalence - the Equivalence to use for values
      expectedSize - an estimate of the number of elements that will be held in the map. If no estimate is known, zero is an acceptable value.
    • CustomConcurrentHashMap

      public CustomConcurrentHashMap()
      Creates a new CustomConcurrentHashMap with strong keys and values, and equality-based equivalence.
  • Method Details

    • newIntKeyMap

      public static <ValueType> CustomConcurrentHashMap<Integer,ValueType> newIntKeyMap(CustomConcurrentHashMap.Strength valueStrength, CustomConcurrentHashMap.Equivalence<? super ValueType> valueEquivalence, int expectedSize)
      Returns a new map using Integer keys and the given value parameters
      Parameters:
      valueStrength - the strength for values
      valueEquivalence - the Equivalence to use for values
      expectedSize - an estimate of the number of elements that will be held in the map. If no estimate is known, zero is an acceptable value.
      Returns:
      the map
    • newIntValueMap

      public static <KeyType> CustomConcurrentHashMap<KeyType,Integer> newIntValueMap(CustomConcurrentHashMap.Strength keyStrength, CustomConcurrentHashMap.Equivalence<? super KeyType> keyEquivalence, int expectedSize)
      Returns a new map using the given key parameters and Integer values
      Parameters:
      keyStrength - the strength for keys
      keyEquivalence - the Equivalence to use for keys
      expectedSize - an estimate of the number of elements that will be held in the map. If no estimate is known, zero is an acceptable value.
      Returns:
      the map
    • newIntKeyIntValueMap

      public static CustomConcurrentHashMap<Integer,Integer> newIntKeyIntValueMap(int expectedSize)
      Returns a new map using Integer keys and values
      Parameters:
      expectedSize - an estimate of the number of elements that will be held in the map. If no estimate is known, zero is an acceptable value.
      Returns:
      the map
    • containsKey

      public boolean containsKey(Object key)
      Returns true if this map contains a key equivalent to the given key with respect to this map's key Equivalence.
      Specified by:
      containsKey in interface Map<K,V>
      Overrides:
      containsKey in class AbstractMap<K,V>
      Parameters:
      key - possible key
      Returns:
      true if this map contains the specified key
      Throws:
      NullPointerException - if the specified key is null
    • get

      public V get(Object key)
      Returns the value associated with a key equivalent to the given key with respect to this map's key Equivalence, or null if no such mapping exists
      Specified by:
      get in interface Map<K,V>
      Overrides:
      get in class AbstractMap<K,V>
      Parameters:
      key - possible key
      Returns:
      the value associated with the key or null if there is no mapping.
      Throws:
      NullPointerException - if the specified key is null
    • put

      public V put(K key, V value)
      Maps the specified key to the specified value in this map.
      Specified by:
      put in interface Map<K,V>
      Overrides:
      put in class AbstractMap<K,V>
      Parameters:
      key - key with which the specified value is to be associated
      value - value to be associated with the specified key
      Returns:
      the previous value associated with key, or null if there was no mapping for key
      Throws:
      NullPointerException - if the specified key or value is null
    • putIfAbsent

      public V putIfAbsent(K key, V value)
      Specified by:
      putIfAbsent in interface ConcurrentMap<K,V>
      Specified by:
      putIfAbsent in interface Map<K,V>
      Returns:
      the previous value associated with the specified key, or null if there was no mapping for the key
      Throws:
      NullPointerException - if the specified key or value is null
    • putAll

      public void putAll(Map<? extends K,? extends V> m)
      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:
      putAll in interface Map<K,V>
      Overrides:
      putAll in class AbstractMap<K,V>
      Parameters:
      m - mappings to be stored in this map
    • replace

      public V replace(K key, V value)
      Specified by:
      replace in interface ConcurrentMap<K,V>
      Specified by:
      replace in interface Map<K,V>
      Throws:
      NullPointerException - if any of the arguments are null
    • replace

      public boolean replace(K key, V oldValue, V newValue)
      Specified by:
      replace in interface ConcurrentMap<K,V>
      Specified by:
      replace in interface Map<K,V>
      Returns:
      the previous value associated with the specified key, or null if there was no mapping for the key
      Throws:
      NullPointerException - if the specified key or value is null
    • remove

      public V remove(Object key)
      Removes the mapping for the specified key.
      Specified by:
      remove in interface Map<K,V>
      Overrides:
      remove in class AbstractMap<K,V>
      Parameters:
      key - the key to remove
      Returns:
      the previous value associated with key, or null if there was no mapping for key
      Throws:
      NullPointerException - if the specified key is null
    • remove

      public boolean remove(Object key, Object value)
      Specified by:
      remove in interface ConcurrentMap<K,V>
      Specified by:
      remove in interface Map<K,V>
      Throws:
      NullPointerException - if the specified key is null
    • isEmpty

      public final boolean isEmpty()
      Returns true if this map contains no key-value mappings.
      Specified by:
      isEmpty in interface Map<K,V>
      Overrides:
      isEmpty in class AbstractMap<K,V>
      Returns:
      true if this map contains no key-value mappings
    • size

      public final int size()
      Returns 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<K,V>
      Overrides:
      size in class AbstractMap<K,V>
      Returns:
      the number of key-value mappings in this map
    • containsValue

      public final boolean containsValue(Object value)
      Returns true if this map maps one or more keys to a value equivalent to the given value with respect to this map's value Equivalence. Note: This method requires a full internal traversal of the hash table, and so is much slower than method containsKey.
      Specified by:
      containsValue in interface Map<K,V>
      Overrides:
      containsValue in class AbstractMap<K,V>
      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:
      NullPointerException - if the specified value is null
    • clear

      public final void clear()
      Removes all of the mappings from this map.
      Specified by:
      clear in interface Map<K,V>
      Overrides:
      clear in class AbstractMap<K,V>
    • computeIfAbsent

      public V computeIfAbsent(K key, CustomConcurrentHashMap.MappingFunction<? super K,? extends V> mappingFunction)
      If the specified key is not already associated with a value, computes its value using the given mappingFunction, and if non-null, enters it into the map. This is equivalent to
         if (map.containsKey(key))
             return map.get(key);
         value = mappingFunction.map(key);
         if (value != null)
            return map.put(key, value);
         else
            return null;
       
      except that the action is performed atomically. Some attempted operations on this map by other threads may be blocked while computation is in progress. Because this function is invoked within atomicity control, the computation should be short and simple. The most common usage is to construct a new object serving as an initial mapped value, or memoized result.
      Parameters:
      key - key with which the specified value is to be associated
      mappingFunction - the function to compute a value
      Returns:
      the current (existing or computed) value associated with the specified key, or null if the computation returned null.
      Throws:
      NullPointerException - if the specified key or mappingFunction is null,
      RuntimeException - or Error if the mappingFunction does so, in which case the mapping is left unestablished.
    • compute

      public V compute(K key, CustomConcurrentHashMap.RemappingFunction<? super K,V> remappingFunction)
      Updates the mapping for the given key with the result of the given remappingFunction. This is equivalent to
         value = remappingFunction.remap(key, get(key));
         if (value != null)
           return put(key, value):
         else
           return remove(key);
       
      except that the action is performed atomically. Some attempted operations on this map by other threads may be blocked while computation is in progress.

      Sample Usage. A remapping function can be used to perform frequency counting of words using code such as:

       map.compute(word, new RemappingFunction<String,Integer>() {
         public Integer remap(String k, Integer v) {
           return (v == null) ? 1 : v + 1;
         }});
       
      Parameters:
      key - key with which the specified value is to be associated
      remappingFunction - the function to compute a value
      Returns:
      the updated value or null if the computation returned null
      Throws:
      NullPointerException - if the specified key or remappingFunction is null,
      RuntimeException - or Error if the remappingFunction does so, in which case the mapping is left in its previous state
    • keySet

      public Set<K> 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.

      The view's iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

      Specified by:
      keySet in interface Map<K,V>
      Overrides:
      keySet in class AbstractMap<K,V>
    • values

      public Collection<V> 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.

      The view's iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

      Specified by:
      values in interface Map<K,V>
      Overrides:
      values in class AbstractMap<K,V>
    • entrySet

      public Set<Map.Entry<K,V>> entrySet()
      Returns 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. 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.

      The view's iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

      Specified by:
      entrySet in interface Map<K,V>
      Specified by:
      entrySet in class AbstractMap<K,V>
    • 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 of the same size, holding keys that are equal using this Map's key Equivalence, and which map to values that are equal according to this Map's value equivalence.
      Specified by:
      equals in interface Map<K,V>
      Overrides:
      equals in class AbstractMap<K,V>
      Parameters:
      o - object to be compared for equality with this map
      Returns:
      true if the specified object is equal to this map
    • hashCode

      public int hashCode()
      Returns the sum of the hash codes of each entry in this map's entrySet() view, which in turn are the hash codes computed using key and value Equivalences for this Map.
      Specified by:
      hashCode in interface Map<K,V>
      Overrides:
      hashCode in class AbstractMap<K,V>
      Returns:
      the hash code