Card 05/ 09

ComparisonDifficulty: Advanced1 min

StackOverflowError Against OutOfMemoryError

Two errors, both fatal, both with the word memory somewhere near them. Which one you got tells you which half of the program to look at, and they have almost nothing in common.

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 fixedHours or days of steady growth
The stack traceThousands of identical framesOrdinary, 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. Thousands 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.