Search code examples
javahashmapsoft-references

HashMap implementation with the soft referenced values


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!


Solution

  • Yes, Guava's CacheBuilder supports both SoftReference and WeakReference values, as well as other eviction policies based on size and time. You can use the Cache directly, or view it as a Map:

    ConcurrentMap<Integer, V> map = CacheBuilder.newBuilder()
       .softValues()
       .build()
       .asMap()