I wanted to test Java WeakHashMap Class functionality and for that matter I wrote the following test:
public class WeakHashMapTest {
public static void main(String args[]) {
Map<String, Object> weakMap = new WeakHashMap<>();
String x = new String("x");
String x1 = new String("x1");
String x2 = new String("x2");
weakMap.put(x, x);
weakMap.put(x1, x1);
weakMap.put(x2, x2);
System.out.println("Map size :" + weakMap.size());
// force all keys be eligible
x=x1=x2=null;
// call garbage collector
System.gc();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Map size :" + weakMap.size());
System.out.println("Map :" + weakMap);
}
}
After running the class WeakMapTest I was unpleasantly surprised to get the following output:
map before gc: {x=x, x1=x1, x2=x2} map after gc: {x=x, x1=x1, x2=x2}
when I expected that the map will be empty.
That is, the garbage collector didn't do its work. But why?