Difference between HashMap and WeakHashMap? in java

www.spiroprojects.com

WeakHashMap is an implementation of Map interface where the memory of the value object can be reclaimed by Grabage Collector if the corresponding key is no longer referred by any section of program. This is different from HashMap where the value object remain in HashMap even if key is no longer referred. We need to explicitly call remove() method on HashMap object to remove the value so that it can be ready to be reclaimed(Provided no other section of program refers to that value object). Calling remove() is an extra overhead.

Here is a simple program which demonstrate the difference:-
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
public class WeakMap {
public static void main(String[] args) {
Map weak = new WeakHashMap();
Map map = new HashMap();
{
String weakkey = new String("weakkey");
weak.put(weakkey,new Object());
String key = new String("key");
map.put(key, new Object());
weakkey = null;
key = null;
}
System.gc();
}

}

Here we create an instance of WeakHashMap and HashMap, populate one value and finally make key to null.  Program calls System.gc() to run garbage collector. Lets see what is the output after running the garbage collector.
Next two image shows the content of two Maps before running GC:-




First two image shows the content of weak and map instance before the GC is called.  weak reference contains a key “weakkey” and corresponding value. Similarly map contains a key “key” and value. Nothing unusual as such.
Next 2 slides contains the value after GC is called. You can see that there is no entry in weak Map. reason is that as we make weakkey as null the corresponsing value is no longer referred from any part of program and eligible for GC. But in case of map  key and value remain seated present in map.

Previous
Next Post »