简单实现Java OutOfMemoryError和StackOverFlowError的方法
本文先不说原理,原理后续再补充,现在只是简单的说下实现方法,有兴趣的同学可以亲自动手试试。
1、实现OutOfMemoryError,直接定义一个大数组即可。
1 public class OutOfMemoryErrorTest { 2 3 public static void main(String[] args) { 4 int[] array = new int[1000000000]; 5 System.out.println(array); 6 } 7 8 }
运行结果如下:
1 Exception in thread "main" java.lang.OutOfMemoryError: Java heap space 2 at com.example.demo.OutOfMemoryErrorTest.main(OutOfMemoryErrorTest.java:6)
2、StackOverFlowError,可以用递归实现。
1 public class StackOverflowErrorTest { 2 3 public static void main(String[] args) { 4 StackOverflowErrorTest test = new StackOverflowErrorTest(); 5 test.foo(); 6 } 7 8 private void foo(){ 9 foo(); 10 } 11 12 }
运行结果:
1 Exception in thread "main" java.lang.StackOverflowError 2 at com.example.spring.demo.StackOverflowErrorTest.foo(StackOverflowErrorTest.java:11)
...