What\'s the difference between StackOverflowError and OutOfMemoryError and how to avoid them in application?
StackOverflowError
happens when you execute too many methods one inside another (for example with an infinite recursion), which is limited by the size of the stack.
OutOfMemoryError
happens when the JVM runs out of space to allocate new objects, which are allocated on the heap.
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 BigObject
s and you will get an OutOfMemoryError
.
To recap:
OutOfMemoryError
is thrown when you are creating objectsStackOverflowError
is thrown when you are calling functionsStackOverflowError
OutOfMemoryError
java.lang.StackOverFlowError:
1) Thrown when stack memory is full
2) The data related to method like parameters, local variables or references to objects are stored in this block. When the method finishes its execution, this block is removed from the stack along with data stored in it.
Whenever you call a method, it must finish its execution and leave the stack memory. If your methods are staying in the stack then stack will be full and JVM will throw java.lang.StackOverflowError.
E.g:
public class FactorialExample
{
private static void factorial(int i)
{
factorial((i+1) * i); //calling itself with no terminating condition
}
public static void main(String[] args)
{
factorial(1);
}
}
java.lang.OutOfMemoryError:
1) Thrown when heap memory is full.
2) JVM is unable to allocate the memory to new objects.
The objects you create in java are stored in the heap memory. When the objects are no more required, they must be removed from the memory. Garbage collector removes the unwanted objects from the heap memory. If your objects have live references, garbage collector doesn’t remove them. It removes only those objects which don’t have live references.
There are two(2) areas in memory the heap and stack.
If there is no memory left in stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError,
while if there is no more heap space for creating object, JVM will throw java.lang.OutOfMemoryError: