java - 如何知道与 WeakHashMap 中已删除条目关联的值

标签 java weak-references weakhashmap

我有这样的东西:

 private Map<MyObj1, MyObj2> map = new WeakHashMap<MyObj1, MyObj2>();

 ... somewhere in the code ...
 MyObj1 myObj1 = new MyObj1();
 map.put(myObj1, new MyObj2();
 ...
 myObj1 = null;

... somewhere else in a thread ... (I would like to pass to a checkThis(MyObj2) method the Value associated with the entry that was removed from the Map)
/* something like this maybe */
while (true) {
    MyObj2 myObj2 = referenceQueue.remove().get();
    checkThis(myObj2);
}

MyObj1 键可能会在 GC 开始运行时被删除,并且没有对它的强引用。

我想将与删除的键关联的特定映射值对象传递给 checkThis(MyObj2)(可能检查 ReferenceQueue?)

我不知道如何将其放入代码中。

最佳答案

引用队列

一旦 WeakReference 开始返回 null,它指向的对象就变成了垃圾并且 WeakReference 对象几乎没有用。这通常意味着需要进行某种清理;例如,WeakHashMap 必须删除此类已失效的条目,以避免持有数量不断增加的无效 WeakReferences。

ReferenceQueue 类可以轻松跟踪无效引用。如果将 ReferenceQueue 传递给弱引用的构造函数,当引用对象指向的对象变为垃圾时,引用对象将自动插入到引用队列中。然后,您可以定期处理 ReferenceQueue 并为死引用执行所需的任何清理工作。

See this page有关如何使用的教程。

您能说明您为什么使用这个吗?有效用途很少。
即缓存不是有效用途(或者至少不是好的用途)

编辑:

此代码等同于使用 weakHashMap,但您需要明确执行此操作以将队列与 map 相关联。

HashMap aHashMap = new HashMap();
ReferenceQueue Queue = new ReferenceQueue();
MyWeakReference RefKey = new MyWeakReference(key, Queue);
aHashMap.put(RefKey, value);

关于java - 如何知道与 WeakHashMap 中已删除条目关联的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3142544/

相关文章:

java - 无法同步(java.util.ConcurrentModificationException)

java - 无法确定这些测试错误的原因,调试器无法在此处运行,我也无法找出解决方法

ios - 在 dispatch_async 函数中使用弱 self

c# - 是否需要 static List<WeakReference>?

具有不可变键的 Java WeakHashMap

java - jsf数据表var属性问题

java - 有没有办法覆盖 openjpa 中的 javax.persistence.EntityManager.persist() 方法

python - 如何在 weakref.finalize 中引用最终对象?

Java Weak Hash Map - 需要根据值的弱点而不是键删除条目

Java7 WeakHashMap isEmpty() 似乎不对