Using soft references in Java

A soft reference is a type of a reference object that you can use to refere to an object but allow it to become garbage collected only if memory is low and no other normal Java reference is pointing to the object. It can be used for caching purposes where a cached object is only of importance in non-critical situations, but is of no importance when the internal memory is low.

The following example demonstrates this. It creates a soft reference to a StringBuffer, fills up the memory to show that only then this reference object will be garbage-collected:

Main.java:

import java.lang.ref.*;
import java.util.*;
import java.io.*;
   
public class Main {
   public static void main(String[] args) {
      SoftReference sr = new SoftReference(createDummyCacheEntry());
 
      printAccessible(sr);
 
      fillUpMemory();
  
      printAccessible(sr);
   }
 
   public static StringBuffer createDummyCacheEntry() {
      System.out.println("Creating dummy cache entry...");
      StringBuffer sb = new StringBuffer();
 
      for (int i=0; i<100000; i++) {
         sb.append("abcdefghijklmnopqrstuvwxyz");
      }
 
      return sb;
   }      
 
   public static void fillUpMemory() {
      System.out.println("Filling up memory...");
      LinkedList ll = new LinkedList();
      try {
         while (true) {
            ll.add(new Double[999999]);
         }
      } catch(OutOfMemoryError e) {
         ll.clear();
         System.gc();
      }
   }
 
   public static void printAccessible(SoftReference sr) {
      System.out.println("Softreference is" + (sr.get() == null ? " not" : "") + " accessible");
   }
}

outputs:

Creating dummy cache entry...
Softreference is accessible
Filling up memory...
Softreference is not accessible