我调查了 WeakHashMap 我们的代码以了解更多关于WeakReference
我发现该条目如下所示:
private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {
V value;
final int hash;
Entry<K,V> next;
/**
* Creates new entry.
*/
Entry(Object key, V value,
ReferenceQueue<Object> queue,
int hash, Entry<K,V> next) {
super(key, queue);
this.value = value;
this.hash = hash;
this.next = next;
}
...
因此,当我们创建新条目时,我们调用super(key, queue);
. 它是WeakReference
构造函数。据我了解,在 GC 收集对象之后,新的引用(我相信它应该是对 的引用key
)将出现在队列中。
我还注意到在每个操作上调用的方法:
/**
* Expunges stale entries from the table.
*/
private void expungeStaleEntries() {
for (Object x; (x = queue.poll()) != null; ) {
synchronized (queue) {
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) x;
int i = indexFor(e.hash, table.length);
Entry<K,V> prev = table[i];
Entry<K,V> p = prev;
while (p != null) {
Entry<K,V> next = p.next;
if (p == e) {
if (prev == e)
table[i] = next;
else
prev.next = next;
// Must not null out e.next;
// stale entries may be in use by a HashIterator
e.value = null; // Help GC
size--;
break;
}
prev = p;
p = next;
}
}
}
}
看起来我们 (Entry<K,V>)
是从队列中获得的。我不知道如何解释这个(第一个问题)。这段代码:
public static void main(String[] args) throws InterruptedException {
StringBuilder AAA = new StringBuilder();
ReferenceQueue queue = new ReferenceQueue();
WeakReference weakRef = new WeakReference(AAA, queue);
AAA = null;
System.gc();
Reference removedReference = queue.remove();
System.out.println(removedReference.get());
}
始终输出 null,因为对象已被 GC 收集
对我来说也很奇怪,我们可以对已经被 GC 收集的 Object 进行引用。实际上我希望引用应该出现在队列中,但我无法读取有意义的内容,因为对象已经收集(第二个问题)。