0%

StackOverflowError与OutOfMemoryError区别

文章字数:306,阅读全文大约需要1分钟

一、StackOverflowError

分析: 栈空间溢出,栈空间是线程私有的,一般用于保存方法体。所以可能是方法体太大或者太多了?

查看源码注释

1
2
3
4
5
6
7
8
9
/**
* Thrown when a stack overflow occurs because an application
* recurses too deeply.
*
* @author unascribed
* @since JDK1.0
*/
public
class StackOverflowError extends VirtualMachineError {

大致意思是:抛出这个异常是因为方法递归太深。也就是每次递归调用新方法都会将上一个方法的运行信息压入栈,当递归太深,导致数据过多,栈空间不足是就会抛出这个错误。

OutOfMemoryError

分析: 内存不足,jvm中方法保存在堆里。应该是内存不够分配新的对象导致的

源码注释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 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.
*
* {@code OutOfMemoryError} objects may be constructed by the virtual
* machine as if {@linkplain Throwable#Throwable(String, Throwable,
* boolean, boolean) suppression were disabled and/or the stack trace was not
* writable}.
*
* @author unascribed
* @since JDK1.0
*/
public class OutOfMemoryError extends VirtualMachineError {

当内存不过创建新对象,gc也不能回收足够的空间时抛出。也就是创建太多的对象实例,或者集合一直扩容此类情况导致的。