Monday, July 5, 2010

Go Soft?

An interesting post that I read sometime ago rakes up this discussion. I'll add the reference to the original post next week.

To give a bit of background we first see what a SoftReference object is. SoftReference is an object which is cleared at the discretion of the garbage collector in response to memory demand. Soft references are most often used to implement memory-sensitive caches. An object that is reachable (only) from a SoftReference is eligible for Garbage collection. The java doc is pretty clear - I recommend reading it!

The problem is the pretty little three line code below,
Object someMethod() { Object o = new MemoryIntensiveObject(); SoftReference<MemoryIntensiveObject> ref = new SoftReference<MemoryIntensiveObject>(o); //Assume garbage collector at this point and needed to free up memory. return ref.get(); }

Is the soft reference bound to return the object that was originally pointed by o ?

1 comment:

  1. Thanks for bringing up such a new topic.
    I am not 100% sure about my answer but I found this while reading the docs.
    " As long as the referent of a soft reference is strongly reachable, that is, is actually in use, the soft reference will not be cleared".
    And since the o and ref are still in use as they are in same method. They will not be cleared, even if u will call System.gc() over there.


Solution for this question?