欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

模拟栈和堆内存溢出

程序员文章站 2022-05-15 21:34:38
...

模拟栈和堆内存溢出

栈内存溢出

public class Demo {
    public static void main(String[] args) {
     // 模拟栈内存溢出
        fun1();
    }
    public static void fun1(){
        long x = 100000*999999999999L;
        fun2();
    }
    public static void fun2(){
        long x = 100000*999999999999L;
        fun3();
    }
    public static void fun3(){
        long x = 100000*999999999999L;
        fun4();
    }
    public static void fun4(){
        long x = 100000*999999999999L;
        fun1();
    }
}

模拟栈和堆内存溢出
利用方法的递归,使本地方法栈内存溢出

模拟堆内存溢出

// public class Demo {
    public static void main(String[] args) {
     // 模拟堆内存溢出
        Fun1 fun6 = new Fun1();
        Fun2 fun = new Fun2();
        Fun3 fun1 = new Fun3();
        Fun4 fun2 = new Fun4();
        Fun5 fun3 = new Fun5();
        Fun6 fun4 = new Fun6();
        Fun7 fun5 = new Fun7();
    }
    static class Fun1{
        Fun2 fun = new Fun2();
        Fun3 fun1 = new Fun3();
        Fun4 fun2 = new Fun4();
        Fun5 fun3 = new Fun5();
        Fun6 fun4 = new Fun6();
        Fun7 fun5 = new Fun7();

    }
    static class Fun2{
        Fun2 fun = new Fun2();
        Fun3 fun1 = new Fun3();
        Fun4 fun2 = new Fun4();
        Fun5 fun3 = new Fun5();
        Fun6 fun4 = new Fun6();
        Fun7 fun5 = new Fun7();
    }
    static class Fun3{
        Fun2 fun = new Fun2();
        Fun3 fun1 = new Fun3();
        Fun4 fun2 = new Fun4();
        Fun5 fun3 = new Fun5();
        Fun6 fun4 = new Fun6();
        Fun7 fun5 = new Fun7();
    }
    static class Fun4{
        Fun2 fun = new Fun2();
        Fun3 fun1 = new Fun3();
        Fun4 fun2 = new Fun4();
        Fun5 fun3 = new Fun5();
        Fun6 fun4 = new Fun6();
        Fun7 fun5 = new Fun7();
    }
    static class Fun5{
        Fun2 fun = new Fun2();
        Fun3 fun1 = new Fun3();
        Fun4 fun2 = new Fun4();
        Fun5 fun3 = new Fun5();
        Fun6 fun4 = new Fun6();
        Fun7 fun5 = new Fun7();
    }
    static class Fun6{
        Fun2 fun = new Fun2();
        Fun3 fun1 = new Fun3();
        Fun4 fun2 = new Fun4();
        Fun5 fun3 = new Fun5();
        Fun6 fun4 = new Fun6();
        Fun7 fun5 = new Fun7();
    }
    static class Fun7{
        Fun2 fun = new Fun2();
        Fun3 fun1 = new Fun3();
        Fun4 fun2 = new Fun4();
        Fun5 fun3 = new Fun5();
        Fun6 fun4 = new Fun6();
        Fun7 fun5 = new Fun7();
    }
}

模拟栈和堆内存溢出
抓住堆内存存储对象,制造堆内存溢出

后期要学会用java提供的工具来看内存占用情况(或者插件)