为什么下面的程序调用了System.exit(0)?只有当map引用变量变为null时才应该调用它。
输出的最后几行如下:
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
public class ReferencesTest {
private WeakReference<Map<Integer, String>> myMap;
public static void main(String[] args) {
new ReferencesTest().doFunction();
}
private void doFunction() {
Map<Integer, String> map = new HashMap<Integer, String>();
myMap = new WeakReference<Map<Integer, String>>(map);
int i = 0;
while (true) {
if (myMap != null && myMap.get() != null) {
myMap.get().put(i++, "test" + i);
System.out.println("im still working!!!!"+i+" Map Size"+myMap.get().size());
System.gc();
} else {
System.out
.println("*******im free*******");
System.exit(0);
}
}
}
}
输出的最后几行如下:
im still working!!!!15586 Map Size15586
im still working!!!!15587 Map Size15587
im still working!!!!15588 Map Size15588
*******im free*******
map
。myMap
是一个弱引用;是的,myMap.get()
返回的确实是变量map
初始化时所使用的相同对象,但它与变量map
没有任何关系。 - Tadas S