Javadocs says “When a key has been discarded its entry is effectively removed from the map”.
But unless there is another thread that occasionally removes such Map.Entry entries, won’t the value objects be strongly referenced by the map? But since there is no such thread running, only the get method invocations can remove such entries – one at a time.
I almost always use WeakHashMap<K, WeakReference<V>> for that reason. Why would they not have made that the default behavior – values as weak references too?
Reference queues are used to automatically remove entries.
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/ref/ReferenceQueue.html
Basically, weak references are a core part of the garbage collector, so when a GC sweep happens, unused references are found and put onto queues and then action can be taken based on the content of those queues.
A thread can sit on the queue’s
removemethod to be alerted when cleanup needs to be done orpollthe queue."Java theory and practice: Plugging memory leaks with weak references" explains:
EDIT:
Even with queues, weak maps can still leak. Ephemerons are an attempt to solve the case where a weak key references a strongly held value that references the key. They are not implementable in java.