Automatically release of a value by WeakReference object


import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;

public class Main {
  public static void main(String[] argv) throws Exception {
    Object keyObject = "";
    Object valueObject = "";
    Map weakMap = new WeakHashMap();

    weakMap.put(keyObject, valueObject);
    WeakReference weakValue = new WeakReference(valueObject);

    weakMap.put(keyObject, weakValue);

    Iterator it = weakMap.keySet().iterator();
    while (it.hasNext()) {
      Object key = it.next();
      weakValue = (WeakReference) weakMap.get(key);
      if (weakValue == null) {
        System.out.println("Value has been garbage-collected");
      } else {
        System.out.println("Get value");
        valueObject = weakValue.get();
      }
    }
  }
}
Home 
  Java Book 
    Runnable examples