Vip*_*pin 3 java reference weak-references map
为什么在下面的程序中调用System.exit(0)?仅当映射引用变量变为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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
最后几行输出
im still working!!!!15586 Map Size15586
im still working!!!!15587 Map Size15587
im still working!!!!15588 Map Size15588
*******im free*******
Run Code Online (Sandbox Code Playgroud)
map在while循环内(或进一步向下)的任何地方都不使用(未引用)VARIABLE .仅仅因为变量仍在范围内,如源中所示; 或者它在方法的字节码中确实有一个指定的局部变量条目,这并不意味着THE VARIABLE map实际上在RURTIME的范围内,特别是在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*******
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
138 次 |
| 最近记录: |