0

I wanted to have a Map with key mapping to quite a big object. Since the map is going to be used as a cache, I wanted to make the values/entries referenced via soft links (java.lang.ref.SoftReference) to clear it on pure memory. But in this case, I need to have my own implementation of computeIfAbsent() method.

I could implement it in the following way:

Map<Integer, SoftReference<T>> myMap = new HashMap<>();

public T get(Integer key) {
    SoftReference<T> value = myMap.get(key);
    if (value == null || value.get() == null) {
        value = new SoftReference(retrieveValue());
        myMap.put(key, value);
    }
    return value.get();
}

Just wanted to know, is there an out of the box solution for such a Map, like java.util.WeakHashMap?

Thanks!

4

1 に答える 1