I try to figure out how the WeakHashMap cleans up after garbare collection. As many of you may know, the WeakHashMap entry is removed automatically when its key becomes garbage collected. But, for instance, if I do something like this:
List<WeakReference<Main>> list = new ArrayList<>();
list.add(new WeakReference<>(new Main()));
System.gc();
Thread.sleep(1000);
list.get(0).get(); //null - WeakReference referent has been removed
list.get(0); //empty WeakReference object is still present in the List
ArrayList doesn't clean the empty WeakReference objects, but why WeakHashMap does? Which component is responsible for this automatic entry removing. I don't see any code in the WeakHashMap sources which could do that.
WeakHashMap cleans itself up. Calls to
getTable()(itself called byget,put, etc.),size()andresize(int)all first call expungeStaleEntries, which iterates a ReferenceQueue of GC'd Entries and removes them from the table. The garbage collector is responsible for putting unreachable WeakReference objects on the queue.