In the code below nameRef.get()
is null , after name = null
and System.gc()
.
import java.lang.ref.WeakReference;
publ
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.