SoftReference and its usage
SoftReference is stronger than WeakReference. It is cleared at the discretion of the garbage collector in response to memory demand. In other words, it will not be collected if there’s enough memory. See below code.
import java.lang.ref.SoftReference;
public class SoftRefTest {
static class Demo {
public String toString() {
return "demo";
}
}
public static void main(String ...args) {
// new Demo referenced by soft only
SoftReference<Demo> soft = new SoftReference<>(new Demo());
System.gc();
try {
Thread.sleep(2000);
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(soft.get()); // print demo
}
}
The Demo instance wrapped in SoftReference will not be collected after manual GC as there’s enough memory space to hold the object.
SoftReference is quite suitable for holding expensive object or cache something. If memory allowed, the referent can stay in memory as long as possible. As a practical example, Guava implements SoftValueReference which wraps cache entry value in SoftReference. It is used when configuring a cache builder with the softValues() method.