When will Java WeakHashMap clean null key?

后端 未结 4 936
悲哀的现实
悲哀的现实 2021-01-14 06:05

In the code below nameRef.get() is null , after name = null and System.gc().

import java.lang.ref.WeakReference;

publ         


        
4条回答
  •  独厮守ぢ
    2021-01-14 07:05

    The simple answer: you don't know.

    Meaning: you have no control when the jvm kicks in and triggers a GC cycle. You have no control when eligible objects are actually collected.

    Thus there is no way for you to know when the "state" of that map changes.

    And yes, the other part is that calling System.gc() is only a recommendation to the jvm to do garbage collection. In a standard setup you have zero control if jvm follows that request, or ignores it. You would need to use very special JVMs for example to change that.

    Typically, gc runs only take place when the jvm considers them necessary. So your map might keep its size at 1 as long as there is no shortage of memory. And as the answer by Holger nicely outlines even the GC running doesn't force the map to update that part.

提交回复
热议问题