如果值包含对键的唯一强引用,是否会收集 WeakHashMap 的条目?

发布于 2024-12-14 02:25:06 字数 359 浏览 9 评论 0原文

我需要将一些数据与键的生命周期相关联,因此我使用了 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倚栏听风 2024-12-21 02:25:06

不,它不会被垃圾收集,请参阅 Javadoc< /a>:

实现说明:WeakHashMap 中的值对象由普通强引用保存。因此,应注意确保值对象不会直接或间接地强烈引用自己的键,因为这将防止键被丢弃。

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

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

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

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.

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);
  }
}
金兰素衣 2024-12-21 02:25:06

看看实施情况,答案似乎是否定的。

这来自 WeakHashMap 源:

/**
 * The table, resized as necessary. Length MUST Always be a power of two.
 */
private Entry[] table;

...

private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {
    private V value;
    ...
}

如您所见,Entry 对象由映射本身强引用。因此,如果地图可访问,Entry、您的 Value 对象以及您的密钥也将可访问。

Looking at the implementation, the answer appears to be no.

This is from the WeakHashMap source:

/**
 * The table, resized as necessary. Length MUST Always be a power of two.
 */
private Entry[] table;

...

private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {
    private V value;
    ...
}

As you can see, Entry objects are referenced strongly by the map itself. So if the map is accessible, so will be the Entry, therefore your Value objects, and your key too.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文