Difference between HashMap and WeakHashMap?

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.

Advertisements

3 responses to “Difference between HashMap and WeakHashMap?

  1. Reblogged this on Devashish Bhattacharjee and commented:
    Nice post on WeakHashMap and HashMap..

  2. Nice explanation! It would be helpful if you mention some real project requirement for using WeakHashmap

  3. Nice Post … easy to understand with example and attached images …

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s