2

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.

  • Recommended reads [How WeakHashMap works under the hood](https://stackoverflow.com/q/41919394/2711488), [When will Java WeakHashMap clean null key?](https://stackoverflow.com/q/54959146/2711488), and [How does a value in an entry in the WeakHashMap gets garbage collected when the actual object is garbage collected?](https://stackoverflow.com/q/50686924/2711488) – Holger Mar 15 '19 at 17:24

1 Answers1

2

WeakHashMap cleans itself up. Calls to getTable() (itself called by get, put, etc.), size() and resize(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.

MikeFHay
  • 8,562
  • 4
  • 31
  • 52