[英]Is there a way to test when an element is removed from a weak set?
In the following snippet (whose only purpose is educational testing), contains()
always ↲ true. 在以下代码段(其唯一目的是教育测试)中,
contains()
始终为true。
Set<String> weakSet = Collections.newSetFromMap(new WeakHashMap<>());
weakSet.add("someKey");
System.gc();
weakSet.contains("someKey");
I would expect that the best effort done by the JVM to reclaim space includes removing objects that are only weakly reachable (weak set elements without any strong references). 我希望JVM回收空间的最大努力包括删除只能弱访问的对象(弱集合元素,而无需任何强引用)。 But I'm wrong.
但是我错了。
So, is there a way to test in practice the automatic removal of weak references, so you can see the reference gone? 那么,有没有一种方法可以在实践中测试自动删除弱引用,以便您可以看到引用消失了? In other words, how to have
contains()
return false? 换句话说,如何让
contains()
返回false?
As @Chai T.Rex properly mentioned in commentaries, strings is bad example for garbage collection. 正如@Chai T.Rex在评论中正确提到的那样,字符串是垃圾收集的不好例子。 To see how objects are garbage collected from weak set try this modified version of your code:
要查看如何从弱集垃圾收集对象,请尝试使用此修改后的代码版本:
Set<Object> weakSet = Collections.newSetFromMap(new WeakHashMap<>());
weakSet.add(new Object());
System.out.println(weakSet.size()); // prints "1"
while (weakSet.size() > 0)
System.gc();
System.out.println(weakSet.size()); // prints "0"
What generally happens here: we add new object into set ( weakSet.add(new Object())
). 这里通常会发生什么:我们将新对象添加到集合中(
weakSet.add(new Object())
)。 But because we do not keep any reference on it, GC will find this object will be removed from set. 但是由于我们没有保留任何引用,GC会发现此对象将从集合中删除。
Loop on GC is needed, as garbage collecting in this simple example case is not guaranteed. 需要在GC上循环,因为不能保证在这种简单示例情况下进行垃圾收集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.