为什么在下面的程序中调用下面的System.exit(0)?只有本地图引用变量变为空时才应调用它。
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
变量在 while
循环(或更往下)内的任何地方都没有使用(未引用)。仅仅因为变量仍在范围内,如源代码所示;或者它在方法的字节码中确实有一个指定的局部变量条目这一事实并不意味着变量 map
实际上在运行时范围内,尤其是在 JIT 编译之后。
除非您使用显式保留未使用的局部变量(在其整个范围内)的选项进行编译,否则这是预期的行为。
证明(--XX:+PrintCompilation
):
im still working!!!!15586 Map Size15586
im still working!!!!15587 Map Size15587
im still working!!!!15588 Map Size15588
259509 23 % eu.revengineer.sync.ReferencesTest::doFunction @ -2 (144 bytes) made not entrant
*******im free*******
关于java - WeakReference 如何影响这个程序的工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20584244/