JVM StackOverflowError vs. OutOfMemoryError

 

if the computation in a thread needs a larger Java Virtual Machine stack than is permitted, the Java Virtual Machine throws a StackOverflowError;

 

if Java Virtual Machine stacks can be dynamically expanded, and expansion is attempted but insufficient memory can be made available to effect the expansion, or if insufficient memory can be made available to create the initial Java Virtual Memory stack for a new thread, the Java Virtual Machine throws an OutOfMemoryError.

 

Example of StackOverflowError: limit the size of a thread's stack size and the do a deep recursion

 1 public class Main {
 2 
 3     public static void main(String[] args) {
 4         new Thread(null, new Runnable() {
 5             public void run() {
 6                 {
 7                     System.out.println(fact(1<<15));
 8                 }
 9             }
10             private long fact(int n) {
11                 return n < 2 ? 1 : n * fact(n-1);
12             }
13         }, "thread", 1<<20).start();
14     }
15 }

 

Example of OutOfMemoryError: limit -Xmx and create large objects (like using StringBuilder)

 1 public class Main2 {
 2 
 3     public static void main(String[] args) {
 4         new Thread(null, () -> {
 5             {
 6                 StringBuilder builder = new StringBuilder();
 7                 for (int cnt = 0; cnt < 100000000; cnt++) {
 8                     builder.append(cnt);
 9                 }
10 
11                 try {
12                     Thread.sleep(15000000);
13                 } catch (InterruptedException e) {
14                     e.printStackTrace();
15                 }
16             }
17         }, "thread", 1 << 20).start();
18     }
19 }

 

转载于:https://www.cnblogs.com/qsort/p/5811938.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值