Java WeakHashMap何时会清理空键? [英] When will Java WeakHashMap clean null key?
问题描述
在nameRef.get()
和System.gc()
之后的nameRef.get()
下面的代码中为null.
In the code below nameRef.get()
is null , after name = null
and System.gc()
.
import java.lang.ref.WeakReference;
public class Main {
public static void main(String[] args) {
String name = new String("ltt");
WeakReference<String> nameRef = new WeakReference<>(name);
System.out.println(nameRef.get()); // ltt
name = null;
System.gc();
System.out.println(nameRef.get()); // null
}
}
WeakHashMap基于WeakReference.最后,我认为map.size()
将为0.实际上是1.
WeakHashMap is based on WeakReference. At last, I think map.size()
will be 0. In fact, it's 1.
import java.util.WeakHashMap;
public class Main2 {
public static void main(String[] args) {
String name = new String("ltt");
WeakHashMap<String, Integer> map = new WeakHashMap<>();
map.put(name, 18);
System.out.println(map.size()); // 1
name = null;
System.gc();
System.out.println(map.size()); // it's 1. why not 0 ?
}
}
Java WeakHashMap何时清理null
键?
When will Java WeakHashMap clean the null
key?
推荐答案
简单的答案:您不知道.
The simple answer: you don't know.
含义:当jvm启动并触发GC周期时,您无法控制.您实际上无法控制何时收集符合条件的对象.
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.
是的,另一部分是调用System.gc()只是对jvm进行垃圾收集的建议.在 standard 设置中,如果jvm遵循该请求或将其忽略,则可以将控制权设为零.例如,您将需要使用非常特殊的JVM来进行更改.
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.
通常,仅当jvm认为有必要时,才会运行gc.因此,只要不占用内存,您的地图就可以保持其大小为1.霍尔格(Holger)的 answer 很好地勾勒出了轮廓,即使GC运行也不会强制地图更新该部分.
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.
这篇关于Java WeakHashMap何时会清理空键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!