JDK1.8源码笔记(9) OutOfMemoryError&StackOverflowError

OutOfMemoryError

前言

 * Thrown when the Java Virtual Machine cannot allocate an object
 * because it is out of memory, and no more memory could be made
 * available by the garbage collector.
当没有更多空间分配给一个对象的时候抛出,连GC都腾不出的那种。

StackOverflowError

前言

* Thrown when a stack overflow occurs because an application
* recurses too deeply.
当一个application递归太深的时候抛出。

Let’s start with the basics. When a method is called, a new stack frame gets created on the call stack. This stack frame holds parameters of the invoked method, its local variables and the return address of the method i.e. the point from which the method execution should continue after the invoked method has returned.

The creation of stack frames will continue until it reaches the end of method invocations found inside nested methods.

During this process, if JVM encounters a situation where there is no space for a new stack frame to be created, it will throw a StackOverflowError.

However, recursion is not the only cause for this error. It can also happen in a situation where an application keeps calling methods from within methods until the stack is exhausted. This is a rare case since no developer would intentionally follow bad coding practices. Another rare cause is having a vast number of local variables inside a method.
递归并非是唯一诱因,如果调用的方法过多或者local variables占据空间太大一样会出问题。

The StackOverflowError can also be thrown when an application is designed to have cyclic relationships between classes. In this situation, the constructors of each other are getting called repetitively which causes this error to be thrown. This can also be considered as a form of recursion.
如果两给类之前循环引用也可能会发生StackOverflowError。
public class Main {
    public static void main(String[] args) {
        new One();
    }
}

class One{
    public Two two = new Two();
}

class Two{
    public One one = new One();
}

Another interesting scenario that causes this error is if a class is being instantiated within the same class as an instance variable of that class. This will cause the constructor of the same class to be called again and again (recursively) which eventually results in a StackOverflowError.
另一种有趣的情况如下,如果类本身的作为自己的实例变量并且被初始化,就会发生递归调用直到溢出。
public class Main {
    public Main main = new Main();
    public static void main(String[] args) {
        Main main = new Main();
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值