Testing WeakReference : SoftReference « Collections Data Structure « Java






Testing WeakReference

  

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    ReferenceQueue referenceQueue = new ReferenceQueue();
    Object object = new Object() {
      public String toString() {
        return "Referenced Object";
      }
    };

    Object data = new Object() {
      public String toString() {
        return "Data";
      }
    };

    HashMap map = new HashMap();
    Reference reference = null;
    System.out.println("Testing WeakReference.");
    reference = new WeakReference(object, referenceQueue);

    map.put(reference, data);

    System.out.println(reference.get());
    System.out.println(map.get(reference));
    System.out.println(reference.isEnqueued());

    System.gc();
    System.out.println(reference.get());
    System.out.println(map.get(reference));
    System.out.println(reference.isEnqueued());

    object = null;
    data = null;

    System.gc();
    System.out.println(reference.get());
    System.out.println(map.get(reference));
    System.out.println(reference.isEnqueued());
  }
}

   
    
  








Related examples in the same category

1.A soft reference holds onto its referent until memory becomes low.
2.A weak reference is used to determine when an object is no longer being referenced.
3.A phantom reference is used to determine when an object is just about to be reclaimed.
4.Testing SoftReference
5.Testing PhantomReference
6.Soft ValueMap
7.An implementation of Set that manages a map of soft references to the set values.
8.Cache based on SoftReference