What's the difference between StackOverflowError and OutOfMemoryError

后端 未结 11 1502
不知归路
不知归路 2020-12-04 09:07

What\'s the difference between StackOverflowError and OutOfMemoryError and how to avoid them in application?

11条回答
  •  无人及你
    2020-12-04 09:43

    Imagine you have a function like the following

    public void f(int x) {
        return f(x + 1);
    }
    

    When you'll call it the call will call f again and again and again. At each call a bit of information is stored on the stack. Since the stack is limited in size you will get a StackOverflowError.

    Now imagine the following code:

    for (int i = 1; i > 0; i++)
        vector.add(new BigObject());
    

    where BigObject is a normal Java object. As you see, the loop never terminates. Each allocation is done on the heap thus it will be filled with BigObjects and you will get an OutOfMemoryError.

    To recap:

    • OutOfMemoryError is thrown when you are creating objects
    • StackOverflowError is thrown when you are calling functions

提交回复
热议问题