简体   繁体   English

关于 Java 虚拟机堆栈溢出

[英]About Java VM Stack Overflow

Thanks!谢谢!

I'm learning JVM, and test VM stack overflow, found a strange phenomenon.我在学习JVM,并测试VM堆栈溢出,发现一个奇怪的现象。 I call a method recursively in two ways, but I was confused with result.我以两种方式递归调用一个方法,但我对结果感到困惑。

VM Options: -Xss108k -Xms10m -Xmx10m虚拟机选项:-Xss108k -Xms10m -Xmx10m

  • only a stack deep counter in method.方法中只有一个堆栈深度计数器。 screenshot 1截图 1

  • I defined array in method, stack go more deeper.我在方法中定义了数组,将 go 堆叠得更深。 screenshot 2截图 2

public class T2 {
    private int stackLength = 1;
    public void stackLeak(){
        long[] a = new long[2000]; //define this array or not
        stackLength++;
        stackLeak();
    }

    public static void main(String[] args) {
        T2 oom = new T2();
        try{ //
            oom.stackLeak();
        } catch(Throwable e){
            System.out.println("stack length: " + oom.stackLength);
            e.printStackTrace();
        } finally{

        }
    }


}

I have re-run many times, results almost the same.我已经重新运行了很多次,结果几乎一样。 I thought, array saved in heap, it won't affect VM stack, but it did.我想,数组保存在堆中,它不会影响 VM 堆栈,但确实如此。

Array allocation affects execution time of the program.数组分配影响程序的执行时间。 The longer the program runs, the more are the chances that JIT compiler will kick in, and the program will continue execution in compiled mode.程序运行的时间越长,JIT 编译器启动的机会就越大,程序将继续以编译模式执行。

The difference in the stack depth is explain by the background JIT compilation.堆栈深度的差异由后台 JIT 编译解释。 See this answer for details.有关详细信息,请参阅此答案

To make the fair comparison, run JVM with JIT compilation turned off: -Xint .为了进行公平比较,请在关闭 JIT 编译的情况下运行 JVM: -Xint In this case, array allocation will make the maximum recursion depth expectedly smaller (since there will one more stack slot used for an array reference).在这种情况下,数组分配将使最大递归深度预期更小(因为将有一个更多的堆栈槽用于数组引用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM