To enable automatically release of the value, the value must be wrapped in a WeakReference object : WeakHashMap « Collections Data Structure « Java






To enable automatically release of the value, the value must be wrapped in a 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();
      }
    }
  }
}

   
    
    
    
    
  








Related examples in the same category

1.Create a WeakHashMap with a single element in it
2.A WeakValueHashMap is implemented as a HashMap that maps keys to Weak Values
3.Implements a combination of WeakHashMap and IdentityHashMap
4.Weak ValueMap
5.Weak Valued HashMap
6.Weak Value HashMap
7.Weak Identity Map
8.A hashtable-based Map implementation with weak keys and using reference-equality in place of object-equality when comparing keys (and values).
9.A hash table with weak keys, full concurrency of retrievals, and adjustable expected concurrency for updates.
10.Map which stores items using SoftReference.