Java测试内存溢出和栈溢出

尝试测试一下Java的内存溢出和栈溢出,

OutOfMemoryErrorstackMemoryError

下面是代码,在 main 方法中分别注释掉另一个,就可以测试了。

 1 public class Main {
 2     public static void main(String[] args) throws Exception {
 3         //headMemoryError();
 4         stackMemoryError();
 5         new CountDownLatch(1).await();
 6     }
 7 
 8     // 使用 -Xss108K 来设置栈大小,设置太小java提示至少108K
 9     private static void stackMemoryError() throws Exception{
10         Thread.sleep(1);
11         stackMemoryError();
12     }
13 
14     // 使用 -Xms5m -Xmx5m 设置堆的最大值和最小值,
15     // 5M好像是堆的最小空间,小于5M,GC会报错
16     private static void headMemoryError(){
17         BigClass b = new BigClass();
18         String[] testData = new String[1024];
19         testData[0] = b.bigData;
20         for(int i = 1; i < 1024; i++){
21             testData[i] = testData[i-1] + testData[i-1];
22         }
23         System.out.println("运行成功");
24     }
25 }

运行结果分别是

栈溢出

  堆溢出

posted @ 2022-04-23 21:14  哦客源  阅读(176)  评论(0)    收藏  举报