JVM 看不到某些异常的stacktrace问题(转)

时间:2021-10-24 15:05:42

在java 1.5的release notes里面可以看到这样一句话:

The compiler in the server VM now provides correct stack backtraces for all "cold" built-in exceptions. 
For performance purposes, when such an exception is thrown a few times, the method may be recompiled.
After recompilation, the compiler may choose a faster tactic using preallocated exceptions that do not provide a stack trace.
To disable completely the use of preallocated exceptions,
use this new flag: -XX:-OmitStackTraceInFastThrow.

大体的意思就是对于cold build-in exception jvm都会throw 没有stacktrace的exception。从1.5开始提供了一个开关关闭此功能

演示代码如下:

public class TestCompile {
private static final int count = 1000000;
/**
* @param args
*/
public static void main(String[] args)throws Exception {
int index = count;
while(index -- > 0){
try {
work();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void work(){
String value = null;
value.length();
}
}

编译后使用java -server  -XX:-OmitStackTraceInFastThrow TestCompile 运行,发现一直都是类似

java.lang.NullPointerException
        at TestCompile.work(TestCompile.java:25)
        at TestCompile.main(TestCompile.java:17)

的stacktrace。

换成java -server -XX:+OmitStackTraceInFastThrow TestCompile 运行一段时间后就会出现

java.lang.NullPointerException
java.lang.NullPointerException
java.lang.NullPointerException
java.lang.NullPointerException
java.lang.NullPointerException
java.lang.NullPointerException
java.lang.NullPointerException
java.lang.NullPointerException
java.lang.NullPointerException

这样的exception,说明stacktrace 该优化已经起作用。-XX:+OmitStackTraceInFastThrow选项在-server情况下默认开启。
这就不难解释为何经常在系统日志中看到很多行的java.lang.NullPointerException 苦于找不到stacktrace而不知道错误出在何处。
遇到这种情况,解决的方法也很简单:既然在一段时间后jvm才会进行重新编译优化,那么该错误在刚开始出现的时候还是会有stacktrace的。所以向前搜索日志,或者将程序重启,观察刚重启时候的log便可以找到错误的stacktrace
最后注意的是,上述优化是针对all "cold" built-in exceptions ,不仅仅是NullPointerException

好,祝大家玩儿的愉快。

Reference:
   1. java 1.5 release notes: http://java.sun.com/j2se/1.5.0/relnotes.html#hotspot
   2. jvm debugging options: http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html#DebuggingOptions

http://blog.csdn.net/alivetime/article/details/6166252