Card 05/ 09

ComparisonDifficulty: Advanced1 min

StackOverflowError vs OutOfMemoryError

Both fatal, both about memory, and they point at opposite halves of the program.

StackOverflowError means one thread's stack (a thread is one path of execution, and its stack holds its chain of method calls) filled up, almost always from recursion that never stops. OutOfMemoryError means the heap (the memory where Java keeps every object) filled up with objects that are still reachable (still connected, through some chain of references, to a variable the program is using). Which one you got tells you where to look.

The two memory failures, on what ran out and what to look for
Compared onStackOverflowErrorOutOfMemoryError
What ran outOne thread's stackThe heap
Caused byToo many nested calls, usually unbounded recursionToo many reachable objects
Time to failureSeconds: the stack is small and fixedOften hours or days of steady growth
The stack traceHundreds of identical frames (the JVM records at most 1024)Ordinary, and at whatever line asked for memory
First thing to checkThe base case of a recursive methodWhat is holding references it no longer needs
java
static int countdown(int n) {
    return countdown(n - 1);
}
no base case, so every call adds a frame and none ever returns

The decision rule for reading one. Look at the trace. Hundreds of repeating frames means the stack, and the fix is in the recursion. A trace that looks like any other, on a line that happens to allocate, means the heap, and the line in the trace is where the last straw landed rather than where the problem is.