消失的异常堆栈---jvm的fast throw

fast throw 简介

HotSpot VM有个许多人觉得“匪夷所思”的优化,叫做fast throw:有些特定的隐式异常类型(NullPointerException、ArithmeticException( / 0)之类)如果在代码里某个特定位置被抛出过多次的话,HotSpot Server Compiler(C2)会透明的决定用fast throw来优化这个抛出异常的地方——直接抛出一个事先分配好的、类型匹配的异常对象。这个对象的message和stack trace都被清空。抛出这个异常的速度是非常快,不但不用额外分配内存,而且也不用爬栈;但反面就是可能正好是需要知道哪里出问题的时候看不到stack trace了。从Sun JDK5开始要避免C2做这个优化还得额外传个VM参数:-XX:-OmitStackTraceInFastThrow。

fast throw复现

public class ExceptionTest {

    public static void main(String[] args) {
        for (int i = 0; i < 1000000; i++) {
            try {
                t();
            } catch (Exception e) {
                if (null != e.getStackTrace() && e.getStackTrace().length <= 0) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void t() {
       int[] nums = new int[1];
       int m = nums[4];

    }
}

结果:
消失的异常堆栈---jvm的fast throw_第1张图片

会进行fast throw 优化的异常

  • NullPointerException
  • ArithmeticException
  • ArrayIndexOutOfBoundsException
  • ArrayStoreException
  • ClassCastException

参考

  • https://juejin.im/post/5a77ba3c5188257a6a78a6e1
  • https://jjlu521016.github.io/2018/12/12/java堆栈信息不见了.html

你可能感兴趣的:(jvm,异常,异常堆栈,jvm,jvm调优,fastthrow)