Saturday 26 July 2014

Soft Reference in Java

An object which is not strongly reachable and and can be accessed through a soft reference is called softly reachable object. All the soft reachable objects will be cleared before JVM throws OutOfMemoryError. In simple terms, Garbage collector clears the Softly reachable objects when memory is needed.

Whenever Garbage collector runs, if it finds an Weakly reachable object, then it clears the memory immediately. It is not the case with softly reachable object, it may or may not clears the softly reachable object. Whether the softly rachable object is freed depends on the algorithm of the garbage collector as well as the amount of memory available while the collector is running.

Garbage Collector interaction with Soft reachable object
If Garbage collector wants to free memory of softly reachable object, then
  1. The soft reference object referent field is set to null.
  2. The heap object referenced by the SoftReference is declared finalizable.
  3. When the heap object's finalize() method is run and its memory freed, the SoftReferenceobject is added to its ReferenceQueue, if it exists.
Creating a SoftReference
SoftReferences are created by passing an object to SoftReference's constructor:

Object obj = new Object();
SoftReference softRef = new SoftReference(obj);

Related Links


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment