What is the difference between OutOfMemoryError and StackOverflowError?
StackOverflowError happens when a thread call stack is exhausted, usually by endless recursion. OutOfMemoryError happens when the heap, or another memory area, cannot supply memory even after garbage collection.
Explain it simply
A stack of plates in a canteen: pile too many on one spot and it topples (StackOverflowError). A godown that is completely full of boxes, with no space for even one more, is OutOfMemoryError.
Example
static int depth(int n) {
return depth(n + 1); // no base case: StackOverflowError
}
static void leak() {
java.util.List<byte[]> list = new java.util.ArrayList<>();
while (true) {
list.add(new byte[10_000_000]); // keeps everything reachable: OutOfMemoryError
}
}What to say in the interview
"Both are Errors, not Exceptions. StackOverflowError is about the per-thread stack and is almost always an infinite or very deep recursion; the fix is a base case or an iterative approach, and -Xss changes the stack size. OutOfMemoryError: Java heap space means live objects fill the heap; it can also say Metaspace or unable to create native thread. I use a heap dump and a tool like Eclipse MAT to find what is holding memory, and increase -Xmx only after confirming it is not a leak."
Common mistakes
- Raising -Xmx as the first response to an OutOfMemoryError caused by a leak.