Demonstrating the WeakHashMap : WeakHashMap « Collections « Java Tutorial






import java.util.Map;
import java.util.WeakHashMap;

public class MainClass {
  private static Map map;

  public static void main(String args[]) {
    map = new WeakHashMap();
    map.put("A", "B");
    Runnable runner = new Runnable() {
      public void run() {
        while (map.containsKey("A")) {
          try {
            Thread.sleep(1000);
            System.gc();
          } catch (InterruptedException ignored) {
          }
          System.out.println("Has A");
          System.gc();
        }
      }
    };
    Thread t = new Thread(runner);
    t.start();
    System.out.println("Main waiting");
    try {
      t.join();
    } catch (InterruptedException ignored) {
    }
    System.gc();
  }
}








9.31.WeakHashMap
9.31.1.WeakHashMap Class
9.31.2.Understanding Weak References
9.31.3.Demonstrating the WeakHashMap
9.31.4.Create a WeakHashMap with a single element in it
9.31.5.To enable automatically release of the value, the value must be wrapped in a WeakReference object
9.31.6.Implements a combination of WeakHashMap and IdentityHashMap