Java WeakHashMap Class

Java WeakHashMap Class

我想测试 Java WeakHashMap Class 功能,为此我编写了以下测试:

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);
}

}    

运行 class WeakMapTest 后,我​​很惊讶地得到以下输出:

gc 之前的映射:{x=x, x1=x1, x2=x2} gc 后映射:{x=x, x1=x1, x2=x2}

当我预计地图将是空的时。

也就是说,垃圾收集器没有完成它的工作。但为什么?

System.gc() 实际上是对 运行 垃圾收集器的 建议 。无法保证强制垃圾收集器运行。

WeakHashMap 的密钥不再是强可达时,垃圾收集器将回收其密钥。

Implementation note: The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys, either directly or indirectly, since that will prevent the keys from being discarded.

但是,由于您使用键本身作为值,该值仍然是强可达的,这意味着垃圾收集器无法回收键。

但是,如果您使用其他对象作为值,那么对键的唯一引用将是键本身。

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

然后,在清除变量并像您已经完成的那样调用垃圾收集器之后,我得到了输出:

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

即使对 System.gc() 的调用不能保证垃圾收集器 运行s,看起来它在这里 运行。