Class WeakKeySoftValueLoadingCache<K,​V>

  • Type Parameters:
    K - the key type
    V - the value type

    public class WeakKeySoftValueLoadingCache<K,​V>
    extends java.lang.Object
    This cache is useful in situations when hard referencing the cache key and the value would otherwise lead to memory or class loader leaks.

    Use use-case is storing a value, like a Class or MethodHandle which is specific to a certain ClassLoader. Holding a strong reference to any of these from the agent code would lead to classloader leaks. That's why the key is wrapped in a WeakReference and the value is wrapped in a SoftReference.

    An otherwise not referenced ClassLoader might still not be collected for a longer time as usual if it is indirectly referenced by the value which is wrapped in a SoftReference. But there is no danger of OOMEs, as the softly referenced value will be collected when memory gets scarce or if it has not been accessed for some time.

    There can also be the situation that a value is collected although it is actually still used. In that case, the value is re-loaded transparently. For frequently accessed values that should not be the case, as a SoftReference works a bit like a LRU cache (see http://xmlandmore.blogspot.com/2014/12/jdk-8-when-softly-referenced-objects.html).

    If the cache key has been collected, the underlying WeakConcurrentMap makes sure that the map entry is deleted.