Java Class WeakHashMap

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());
    // 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 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?

+4
source share
2 answers

WeakHashMap will have its keys recovered by the garbage collector when they can no longer reach the goal.

: WeakHashMap . , , , .

, , , , .

, , .

weakMap.put(x, new Object());
weakMap.put(x1, new Object());
weakMap.put(x2, new Object());

, , :

Map size :3
Map size :0
Map :{}

System.gc() , , .

+5

System.gc() - . .

+1

Source: https://habr.com/ru/post/1570088/


All Articles