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:

import java.lang.ref.*;
import java.util.*;
public class Main {
   public static void main(String[] args) {
      SoftReference sr = new SoftReference(createDummyCacheEntry());
   public static StringBuffer createDummyCacheEntry() {
      System.out.println("Creating dummy cache entry...");
      StringBuffer sb = new StringBuffer();
      for (int i=0; i<100000; i++) {
      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) {
   public static void printAccessible(SoftReference sr) {
      System.out.println("Softreference is" + (sr.get() == null ? " not" : "") + " accessible");


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