我有一个以下代码来测试GC存储在地图中的弱引用。
public static void main(String[] args) {
Map<String, WeakReference<Person>> map = new HashMap<String, WeakReference<Person>>();
for (int i = 0; i < 5000; i++) {
Person person = new Person("weak_id"+ i, "hello"+ i, "smith"+ i, "hello@hotmail.com"+ i);
map.put("id"+i, new WeakReference(person));
person = null;
}
Map<String, Person> cache = new HashMap<String, Person>();
for (int i = 0; i < 9000; i++) {
Person person = new Person("id"+ i, "hello"+ i, "smith"+ i, "hello@hotmail.com"+ i);
cache.put("id"+i, person);
}
// Make a breakpoint here and perform 'Perform GC' on the jconsole
// and let the following code continue to see if it is discarded by GC
for (int i = 0; i < 5000; i++) {
WeakReference ref = map.get("id"+i);
if (ref == null || ref.get() == null) {
continue;
}
System.out.println(ref.get());
}
for (int i = 50001; i < 10000; i++) {
Person person = new Person("later_id"+ i, "hello"+ i, "smith"+ i, "hello@hotmail.com"+ i);
map.put("later_id"+i, new WeakReference(person));
}
System.out.println("hello");
}
我试图找出GC是否实际上回收了为地图存储分配的内存5000 WeakReference引用Person实例。我将'finalize'方法添加到Person对象中,并在GC启动时打印出每个实例变量的值,以便我可以看到GC启动。
当我在jconsole上触发'Perform GC'时,我看到了打印输出消息。我猜这意味着GC回收为50000 Person实例分配的内存。
但是在Eclipse调试模式下,即使存储在地图中的WeakReferences似乎是垃圾收集的,我仍然看到5000的大小而不是空地图。
是否意味着即使GC丢弃了5000个人实例,HashMap仍然在地图中保留了5000个空格吗?