如果值包含对密钥的唯一强引用,是否会收集WeakHashMap的条目? [英] Will a WeakHashMap's entry be collected if the value contains the only strong reference to the key?

查看:148
本文介绍了如果值包含对密钥的唯一强引用,是否会收集WeakHashMap的条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一些数据与密钥关联起来,因此我使用 WeakHashMap 。但是,另外我需要通过其相应的值获取密钥。简单的方法是在创建值时保留引用:

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?

推荐答案

不,它不会被垃圾收集,请参阅 Javadoc

No it won't be garbage collected, see the Javadoc:


实现注意事项: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.

正如@biziclop所提到的,一个解决方案是在您的价值对象中存储对该键的弱引用。

As mentioned by @biziclop one solution would be to store a weak reference to the key in your value object.

public class Value { 
  final public WeakReference<Key> key;
  public Value(Key k) {
    this.key = new WeakReference<Key>(k);
  }
}

这篇关于如果值包含对密钥的唯一强引用,是否会收集WeakHashMap的条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆