I invesigate WeakHashMap ource code to have more knowledge about WeakReference
I have found that entry looks like this:
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;
}
...
Thus when we create new entry we invoke super(key, queue);
. It is WeakReference
constructor. As far I understand after object will be collected by GC the new reference(I believe it should be reference on key
) will be appeared in the queue.
Also I have noticed method which invokes on each operation:
/**
* 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;
}
}
}
}
Looks like we get (Entry<K,V>)
from queue. I don't know how to explain this(first question).
this code:
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());
}
always outputs null, because object already collected by GC
Also for me it was strange that we can have reference on Object which was already collected by GC. Actually I expect that reference should appear in queue but I could not read something meaningful because object already collected(second question).