AWeakHashMap
几乎可以与 aWeakReference
结合使用ReferenceQueue
- 关于此的新闻为零。这是一个关于它应该如何工作的精简示例:
public class ReferenceQueuePlayground {
public static void main(String[] args) {
ReferenceQueue<Referent> q = new ReferenceQueue<>();
Referent ref = new Referent();
WeakReference<Referent> weak = new WeakReference<>(ref, q);
ref = null;
// wait for GC to reclaim Referent
while (weak.get() != null) {
System.gc();
}
// this might return null, because ReferenceQueue is notified asynchronously
// but I am assuming the happy path here
Reference<? extends Referent> reference = q.poll();
// this will be false
System.out.println(reference == null);
// this will be true
System.out.println(reference.get() == null);
}
@RequiredArgsConstructor
@Getter
static class Referent {
}
}
这正是它WeakHashMap
的工作原理——当referent
被回收并将reference
放在ReferenceQueue
. 在一些后续的操作中,expungeStaleEntries
被调用,它基本上会从这个元素中ReferenceQueue
一个一个地获取元素并对其进行操作。
referent
我的问题是:如果现在消失了,它如何“对他们采取行动” ?毕竟这是 a ...HASHMap
,所以为了移除元素,它必须知道它是hashCode
. 你怎么知道hashCode
现在已经消失的东西?