I wanted to test the functionality of the Java WeakHashMap Class and, for that matter, 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());
x=x1=x2=null;
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 WeakMapTest class, I was unpleasantly surprised to receive the following output:
before gc: {x = x, x1 = x1, x2 = x2} map after gc: {x = x, x1 = x1, x2 = x2}
when I expected the card to be blank.
That is, the garbage collector did not do its job. But why?
source
share