Chabuduo001
V2EX  ›  问与答

请教大佬关于 Java 虚拟机栈的问题

  •  1
     
  •   Chabuduo001 · May 23, 2019 · 1777 views
    This topic created in 2578 days ago, the information mentioned may be changed or developed.

    想测试一下关于每个栈帧大小对于栈深度的影响。栈大小设置为-Xss160k

    public class TestStack {
    
        public static int i;
    
        public static void main(String[] args) {
            test();
        }
    
        public static void test(){
            System.out.println(i++);
            test2();
        }
    
        public static void test2(){
    
            System.out.println(i++);
            test();
        }
    }
    
    

    这样跑的话,大概 i 跑出的数字到 830 就栈溢出了,所以我在每个方法中添加了变量,例如

       public static void test2(){
            int i1 =10000;
            int i2 =10000;
            int i3 =10000;
            int i4 =10000;
            int i5 =10000;
            System.out.println(i++);
            test();
        }
    
    

    而这样跑的话大概 i 跑到 560 左右就栈溢出了,随后我建了一个对象

    class StackCount{
    
        int i = 100000;
        int i2 = 100000;
        int i3 = 100000;
        int i4 = 100000;
        int i45= 100000;
        int i455= 100000;
        int i4555= 100000;
    }
    
    

    方法改为如下

    public static void test2(){
            for (int j = 0; j < 100; j++) {
                StackCount stackCount = new StackCount();
            }
            System.out.println(i++);
            test();
        }
    
    

    不断的在对象里面添加 int 属性的同时,栈深度也在不断的变小。

    于是问题就来了,栈帧的大小为什么会随着对象大小变化呢?对象不是存放在堆内存中吗?栈帧不是只存放地址吗?

    希望有大佬可以给解答一下。

    cyspy
        1
    cyspy  
       May 23, 2019
    基本类型和对象的引用在栈上,另外还和调用的函数参数数量有关,栈帧大小是在编译期确定的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2998 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 03:50 · PVG 11:50 · LAX 20:50 · JFK 23:50
    ♥ Do have faith in what you're doing.