Monthly Archives: February 2015

Difference between HashMap and WeakHashMap?

Nice post on WeakHashMap and HashMap..

Vivek's Tech Blog

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;




View original post 141 more words


We can differentiate between the three using a very nice diagrammatic approach collected from the internet. Here is a brief description on the three.


JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.

The JVM performs following main tasks:

  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

JRE :  JRE consistes of JVM and other libraries like rt.jar etc.

JDK: Along with JVM and JRE , JDK consists of the actual development tools such as javac and java.

The diagrammatic approach shown in   link is very helpful.