WeakHashMap - Java
WeakHashMap is an implementation of Map interface where the memory of the value object can be reclaimed by Garbage 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();
}
}
Reference: https://techvivek.wordpress.com/2012/09/11/difference-between-hashmap-and-weakhashmap/
Comments
Post a Comment