SoftReference vs. WeakReference

At first sight SoftReference doesn't look much different from WeakReference. Actually, if you compare the example you can see here below, and the one I wrote for SoftReference, they will look almost identical.

What changes is all in the expected surviving time for an object that is not associated anymore to any strong reference. If it has at least one soft reference it should survive longer than if it had only weak references. We could say that the Java garbage collector turns a more gentle eye to soft references while it is stricter against weak references.

What it the point using soft references? Caching, maybe.

I loaded an object in memory, it has completed its job, and now it could be discarded. Still there is a chance someone will ask again for it soon, and loading it again is a bit expensive. We don't have a strong opinion on how long it should stay alive, and when it will be more worthy to get rid of it. We don't know how to take such a decision, so we let JVM deciding for us.
String strong = new String("A string");
SoftReference<String> soft = new SoftReference<String>(strong);

System.out.println("Setup: " + strong);
strong = null;

int[][] ia = new int[10][];
for(int i = 0; i < 10; ++i) {
    if(sa.get() == null) {
        System.out.println("Removed");
        return;
    }
    System.out.println(i + "] looping on " + sa.get());
    ia[i] = new int[150000];
}
System.out.println("Not removed!?");
If you run this code, and compare it with the same stuff but using WeakReference instead, you should find out a similar behavior, but a different number of loops performed before the garbage collector takes the decision to kill the object.

No comments:

Post a Comment