Search This Blog

Tuesday, 18 February 2014

Soft References in Java

In the last post I looked at using weak references in my java code. As we saw Java has not just strong and weak but also soft and phantom references.
Firstly, what are soft references ?
I modified my earlier code - running it with SoftReference instead of WeakReference:
public static void main(String[] args) {

      List<SoftReference<SavePoint>> savePoints = new ArrayList<SoftReference<SavePoint>>();
      SoftReference<List<SoftReference<SavePoint>>> weakList = new SoftReference<List<SoftReference<SavePoint>>>(
            savePoints);

      SavePoint savePoint = null;
      Set<SavePoint> savePointsToHold = new LinkedHashSet<SavePoint>();
      for (int i = 0; i < 5; i++) {
         savePoint = new SavePoint("This is savepoint No " + i);
         weakList.get().add(new SoftReference<SavePoint>(savePoint));
      }
      // the last savepoint is a strong reference
      savePointsToHold.add(savePoint);

      final Runtime RUNTIME = Runtime.getRuntime();
      System.out.println("total memory : " + RUNTIME.totalMemory() + ", free memory : " + RUNTIME.freeMemory());

      System.out.println("Now to call gc...");
      RUNTIME.gc();
      System.out.println("total memory : " + RUNTIME.totalMemory() + ", free memory : " + RUNTIME.freeMemory());
      for (int i = 0; i < 5; i++) {
         System.out.println("Value at location " + i + " is " + weakList.get().get(i).get());
      }

   }
The output is as below:
total memory : 61800448, free memory : 61153048
Now to call gc...
total memory : 61800448, free memory : 61227984
Value at location 0 is SavePoint [content : This is savepoint No 0, actionTime : Thu Oct 17 23:58:52 IST 2013
Value at location 1 is SavePoint [content : This is savepoint No 1, actionTime : Thu Oct 17 23:58:52 IST 2013
Value at location 2 is SavePoint [content : This is savepoint No 2, actionTime : Thu Oct 17 23:58:52 IST 2013
Value at location 3 is SavePoint [content : This is savepoint No 3, actionTime : Thu Oct 17 23:58:52 IST 2013
Value at location 4 is SavePoint [content : This is savepoint No 4, actionTime : Thu Oct 17 23:58:52 IST 2013
As seen above the gc run resulted in freeing of memory. But the list of soft references remained. The garbage collector will always collect weakly referenced objects, but will only collect softly referenced objects when its algorithms decide that memory is low enough to warrant it.
Thus with soft references, the gc behavior is slightly more memory sensitive. The above objects would have been garbage collected if the free memory available was very low.
The last type of memory reference is a phantom reference. This type has slightly different characteristics and will require an understanding of ReferenceQueues. More on this later.

No comments:

Post a Comment