2013-04-06 82 views
2

我遵循的測試類檢查JIT編譯器的邏輯:Java 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版本:

的Java(TM)SE運行時環境(建立1.7.0_17-B02)

爪哇熱點(TM)64位服務器VM(構建23.7-B01,混合模式)

UPDATE:PrintCompilation輸出:

79 1 %   com.nau.sample.deadcode.TestDeadCode::getSum @ 7 (34 bytes) 

85 1    com.nau.sample.deadcode.TestDeadCode::getSum (34 bytes) 
+0

其實最有可能的(如果'LOG.isDebug()'在編譯時是已知的)存在的javac行爲,而不是JIT編譯器。 – 2013-04-06 22:15:22

+1

javac無法預測「LOG.isDebug()」值。 – anstarovoyt 2013-04-06 22:16:42

+0

你可以看到System.out.println(IS_DEBUG)在setFinalStatic() – anstarovoyt 2013-04-06 22:19:46

回答