Create a WeakHashMap with a single element in it : WeakHashMap « Collections Data Structure « Java






Create a WeakHashMap with a single element in it

     


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

public class Main {
  public static void main(String args[]) {
    final Map<String, String> map = new WeakHashMap<String, String>();
    map.put(new String("A"), "B");
    Runnable runner = new Runnable() {
      public void run() {
        while (map.containsKey("A")) {
          try {
            Thread.sleep(500);
          } catch (InterruptedException ignored) {
          }
          System.gc();
        }
      }
    };

    Thread t = new Thread(runner);
    t.start();
    try {
      t.join();
    } catch (InterruptedException ignored) {
    }
  }
}

   
    
    
    
    
  








Related examples in the same category

1.To enable automatically release of the value, the value must be wrapped in a WeakReference object
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.