关于 Java 虚拟机堆栈溢出

huangapple go评论64阅读模式
英文:

About Java VM Stack Overflow

问题

Thanks!

我正在学习JVM,并测试VM堆栈溢出,发现了一个奇怪的现象。
我以两种方式递归调用一个方法,但结果让我感到困惑。

VM选项:-Xss108k -Xms10m -Xmx10m

  • 方法中只有一个堆栈深度计数器。
    截图1

  • 我在方法中定义了数组,堆栈深度增加了。
    截图2

public class T2 {
    private int stackLength = 1;
    public void stackLeak(){
        long[] a = new long[2000]; //是否定义这个数组都一样
        stackLength++;
        stackLeak();
    }

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

        }
    }
}

我已经重新运行了很多次,结果几乎相同。
我原以为数组保存在堆中,不会影响VM堆栈,但实际上会影响。

英文:

Thanks!

I'm learning JVM, and test VM stack overflow, found a strange phenomenon.
I call a method recursively in two ways, but I was confused with result.

VM Options: -Xss108k -Xms10m -Xmx10m

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.

答案1

得分: 1

数组分配会影响程序的执行时间。程序运行时间越长,JIT编译器介入的可能性就越大,程序将在编译模式下继续执行。

栈深度的差异是由后台JIT编译解释的。有关详细信息,请参阅此答案

为了进行公平比较,请关闭带有JIT编译的JVM:-Xint。在这种情况下,数组分配将使最大递归深度预期地变得更小(因为将使用一个额外的栈槽来存储数组引用)。

英文:

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.

The difference in the stack depth is explain by the background JIT compilation. See this answer for details.

To make the fair comparison, run JVM with JIT compilation turned off: -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).

huangapple
  • 本文由 发表于 2020年4月5日 12:03:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/61037893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定