Pages

January 24, 2012

Weak Hash Map Example


Please find one simple example of usage of Weak Hash Map.

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


public class WeakHashMapExample {

 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")) {
        System.out.println("map contains key A");
        try { Thread.sleep(500);}
        catch (InterruptedException ignored) {}        
        //System.gc();
       }
     }
   };
 

   Iterator it = map.keySet().iterator();
   while (it.hasNext()) {
     Object key = it.next();
     Object weakValue = map.get(key);
     if (weakValue == null) {System.out.println("Value has been garbage-collected");}
     else {System.out.println("Get value:" + weakValue);}    
     }


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


1 comment: