1
package com.atul;

public class StackOverFlow {

    public StackOverFlow() {
        callStackOverFlow();
    }

    public void callStackOverFlow() {
        StackOverFlow st = new  StackOverFlow();
    }

    public static void main(String[] args) {
        StackOverFlow st2 = new StackOverFlow();
    }
}

在上面的程序中,我试图得到 OutOfMemory 错误,但我得到 StackOverFlow 错误。据我所知,所有对象都是在堆中创建的。在这里,我们正在使用构造函数进行递归,但仍然出现 StackOverFlow 错误。

为什么?

4

3 回答 3

7

You run out of stack (which has a maximum depth around 10,000 for simple cases) long before you run out of heap memory. This is because every thread has its own stack so it must be a lot smaller than the shared heap.

If you want to run out of memory, you need to use up the heap faster.

public class OutOfMemoryMain {
    byte[] bytes = new byte[100*1024*1024];
    OutOfMemoryMain main = new OutOfMemoryMain();

    public static void main(String... args) {
        new OutOfMemoryMain();
    }
}
于 2012-10-02T08:25:08.230 回答
1

The stack size in the JVM is limited (per-thread) and configurable via -Xss.

If you want to generate an OOM, I would suggest looping infinitely and instantiating a new object per loop, and storing it in a collection (otherwise the garbage collection will destory each instance)

于 2012-10-02T08:25:05.920 回答
0

在内存充满对象和程序因内存不足而中止之前;你用完了存储方法调用的堆栈,因此你得到了 Stackoverflow 错误。

当您的对象填满堆空间时会出现溢出错误......

于 2012-10-02T08:27:05.307 回答