jvm栈深度

什么是栈深度

每个jvm虚拟机的内存大小都是有限的,jvm虚拟机主要包括堆、虚拟机栈、本地(native)方法栈、程序计数器、方法区……此处说的栈指的是虚拟机栈。这个虚拟机栈的大小是 有限的,如果在同一个时刻执行很多方法(用极限的思想,假设有接近无穷个函数在同一个时间点执行),那所需要的内存是巨大的,超过了栈内存大小,就抛出栈溢出(StackOverflow)异常。栈深度可以通过函数调用自身,同时记录调用的次数,来计算,这个次数指的是当程序StackOverflow时的大小。

demo

public class StackDepth {
    
    
    private int depth;

    public void test(int i) {
    
    
        depth++;
        test(0);
    }

    public void getDepth() {
    
    
        test(0);
    }

    public static void main(String[] args) {
    
    
        StackDepth stackDepth = new StackDepth();
        try {
    
    
            stackDepth.test(0);
        } catch (StackOverflowError e) {
    
    
            System.out.println(stackDepth.depth);
        }
    }
}

因为每个函数所占用的栈大小,在编译的时候就是确定好的,当你这个函数有参数时,这个函数需要的栈内存肯定大一些,所以参数的个数也会影响栈深度大小

猜你喜欢

转载自blog.csdn.net/chen462488588/article/details/112793892