Class SingletonMap<K,​V>

  • Type Parameters:
    K - The key type.
    V - The value type.

    public abstract class SingletonMap<K,​V>
    extends Object
    A map from keys to singleton instances. Allows you to create object instance singletons and add them to a ConcurrentMap on demand, based on a key value. Works the same as concurrentMap.computeIfAbsent(key, key -> newInstance(key)), except that it also works on JDK 7.
    • Constructor Detail

      • SingletonMap

        public SingletonMap()
    • Method Detail

      • newInstance

        public abstract V newInstance​(K key,
                                      LogNode log)
                               throws Exception
        Construct a new singleton instance.
        Parameters:
        key - The key for the singleton.
        log - The log.
        Returns:
        The singleton instance.
        Throws:
        Exception - If something goes wrong.
      • get

        public V get​(K key,
                     LogNode log)
              throws Exception
        Check if the given key is in the map, and if so, return it. If not, create a singleton value for that key, and return the created value. Stores null in the map if creating a new singleton instance failed due to throwing an exception, so that the failed operation is not repeated twice, however throws IllegalArgumentException if during this call or a previous call for the same key, newInstance(Object, LogNode) returned null.
        Parameters:
        key - The key for the singleton.
        log - The log.
        Returns:
        The singleton instance, if newInstance(Object, LogNode) returned a non-null instance on this call or a previous call.
        Throws:
        Exception - if newInstance(key) throws an exception.
        IllegalArgumentException - if newInstance(key) returns null.
      • getIfPresent

        public V getIfPresent​(K key)
                       throws InterruptedException
        Get the singleton for a given key, if it is present in the map, otherwise return null. (Note that this will also return null if creating a singleton value for a given key failed due to throwing an exception.)
        Parameters:
        key - The key for the singleton.
        Returns:
        the new singleton instance, initialized by calling newInstance, or null if createSingleton() or getOrCreateSingleton() has not yet been called. Also returns null if newInstance() threw an exception or returned null while calling either of these methods.
        Throws:
        InterruptedException - If getting the singleton was interrupted.
      • clear

        public void clear()
        Clear the map.