我有以下测试类来检查 JIT 编译器逻辑:
public static final int COUNT = 2_000_000_000;
public static final MyLogger LOG = new MyLogger(false);
//Here IS_DEBUG is false
public static final boolean IS_DEBUG = LOG.isDebug();
private void run() throws Exception
{
System.out.println(getSum(COUNT));
//Compilation without OSR
System.out.println(getSum(COUNT + 2));
//Change value IS_DEBUG -> true over reflection
setFinalStatic(TestDeadCode.class.getField("IS_DEBUG"), true);
//Show true
System.out.println(IS_DEBUG);
COUNT = COUNT / 2;
System.out.println(getSum(COUNT + 3));
}
private int getSum(int count)
{
int result = 0;
for (int j = 0; j < count; j++)
{
result = result + 1;
if (IS_DEBUG)
{
//Dead code here
System.out.println("debug: " + result);
}
}
return result;
}
如果我调用方法run()
然后是“死代码”
System.out.println("debug: " + result);
永远不会被执行。它是JVM错误吗?
爪哇版:
Java(TM) SE 运行时环境 (build 1.7.0_17-b02)
Java HotSpot(TM) 64 位服务器 VM(内部版本 23.7-b01,混合模式)
更新:打印编译输出:
79 1 % com.nau.sample.deadcode.TestDeadCode::getSum @ 7 (34 bytes) 85 1 com.nau.sample.deadcode.TestDeadCode::getSum (34 bytes)