我试图弄清楚在收集垃圾后 WeakHashMap 是如何清理的。许多人可能知道,当 WeakHashMap 的键被垃圾回收时,它会自动删除。但是,例如,如果我做这样的事情:
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 不会清除空的 WeakReference 对象,但为什么 WeakHashMap 会呢?哪个组件负责此自动条目删除。我在 WeakHashMap 源代码中看不到任何可以做到这一点的代码。