How about something like this SingletonCache class from one of my projects?
public abstract class SingletonCache<K, V> { private final ConcurrentMap<K, V> cache = new ConcurrentHashMap<K, V>(); public V get(K key) { V value = cache.get(key); if (value == null) { cache.putIfAbsent(key, newInstance(key)); value = cache.get(key); } return value; } protected abstract V newInstance(K key); }
To use it, you extend it and implement the newInstance method, which creates a new value in the event of a cache miss. Then call the get method with the key to get the instance corresponding to that key. Here is an example of how it is used.
This class ensures that only one instance is returned for each key, but the newInstance method can be called several times, in which case the first computed instance is used, and the rest are discarded. Also note that this cache does not delete old instances, but retains all values โโindefinitely (in my case, a limited number of instances are used that need to be cached). Reading from ConcurrentHashMap does not use locking, so it must satisfy performance requirements.
source share