如果值包含对键的唯一强引用,是否会收集 WeakHashMap 的条目?
我需要将一些数据与键的生命周期相关联,因此我使用了 WeakHashMap
。但是,此外我还需要通过其对应的值来获取密钥。最简单的方法是在创建值时保留引用:
public class Key {}
public class Value {
final public Key key;
public Value(Key k) {
key = k;
}
}
当然,当我在程序中使用 Value
时,它的 key
不会消失。但是,如果映射之外不再有对任一键或其值的引用,它会被垃圾收集吗?或者值中幸存的强引用是否会阻止它?
I need to associate some data with a key for its lifetime, so I am using a WeakHashMap
. However, in addition I need to get a key by its corresponding value. The easy way to do it is to hold on to the reference when creating a value:
public class Key {}
public class Value {
final public Key key;
public Value(Key k) {
key = k;
}
}
Of course, while I use Value
in my program, its key
won't go away. However, if there are no more references to either key or its value outside the map, will it be garbage collected? Or does the surviving strong reference in the value prevent it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,它不会被垃圾收集,请参阅 Javadoc< /a>:
正如 @biziclop 所提到的,一种解决方案是在值对象中存储对键的弱引用。
No it won't be garbage collected, see the Javadoc:
As mentioned by @biziclop one solution would be to store a weak reference to the key in your value object.
看看实施情况,答案似乎是否定的。
这来自
WeakHashMap
源:如您所见,
Entry
对象由映射本身强引用。因此,如果地图可访问,Entry
、您的Value
对象以及您的密钥也将可访问。Looking at the implementation, the answer appears to be no.
This is from the
WeakHashMap
source:As you can see,
Entry
objects are referenced strongly by the map itself. So if the map is accessible, so will be theEntry
, therefore yourValue
objects, and your key too.