Sobes.tech
Senior

In what cases is it useful to use a soft reference?

sobes.tech AI

Answer from AI

Soft references (WeakReference in Java) are useful when you need to keep objects in memory but do not want to prevent their garbage collection when memory is low. For example, a cache that should not keep objects alive if they are not used elsewhere. This helps avoid memory leaks and allows the JVM to manage resources efficiently.

Example of using a soft reference for a cache:

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

public class Cache<K, V> {
    private Map<K, SoftReference<V>> cache = new HashMap<>();

    public void put(K key, V value) {
        cache.put(key, new SoftReference<>(value));
    }

    public V get(K key) {
        SoftReference<V> ref = cache.get(key);
        return (ref != null) ? ref.get() : null;
    }
}

Thus, if the object is needed, it will be returned from the cache, but if necessary, the JVM can free it.