1. 程式人生 > >強制要求JVM始終丟擲含堆疊的異常(-XX:-OmitStackTraceInFastThrow)

強制要求JVM始終丟擲含堆疊的異常(-XX:-OmitStackTraceInFastThrow)

問題描述:生產環境拋異常,但卻沒有將堆疊資訊輸出到日誌,可以確定的是日誌輸出時用的是log.error("xx發生錯誤", e)
問題分析:它跟JDK5的一個新特性有關,對於一些頻繁丟擲的異常,JDK為了效能會做一個優化,即JIT重新編譯後會丟擲沒有堆疊的異常
          而在使用-server模式時,該優化選項是開啟的,因此在頻繁丟擲某個異常一段時間後,該優化開始起作用,即只丟擲沒有堆疊的異常資訊
問題解決:由於該優化是在JIT重新編譯後才起作用,因此起初丟擲的異常還是有堆疊的,所以可以檢視較舊的日誌,尋找完整的堆疊資訊
          另一個解決辦法是暫時禁用該優化,即強制要求每次都要丟擲有堆疊的異常,幸好JDK提供了通過配置JVM引數的方式來關閉該優化
          即-XX:-OmitStackTraceInFastThrow,便可禁用該優化了(注意選項中的減號,加號則表示啟用)
官方說明: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.