编程语言
首页 > 编程语言> > Java WeakHashMap类

Java WeakHashMap类

作者:互联网

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

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

}    

运行WeakMapTest类后,我得到以下输出令人不快惊讶:

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

当我预计地图将是空的.

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

解决方法:

当垃圾收集器不再可以强烈访问时,它将由垃圾收集器回收它的密钥.

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()的调用不能保证垃圾收集器运行,它看起来确实在这里运行.

标签:java,garbage-collection,weak-references,weakhashmap
来源: https://codeday.me/bug/20190528/1171807.html