In the code below nameRef.get()
is null , after name = null
and System.gc()
.
import java.lang.ref.WeakReference;
publ
System.gc()
only suggests a garbage collection. There are no guarantees made on when and even if the collection will happen. You are seeing exactly that, you made the suggestion but it was not done yet.
See the documentation:
[...] Calling the
gc
method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects. [...]
Having said that, there is no way for you to know when the entry in the map is gone, except checking it regularly.