Card 05/ 09
All 9 cards
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.
| Compared on | StackOverflowError | OutOfMemoryError |
|---|---|---|
| What ran out | One thread's stack | The heap |
| Caused by | Too many nested calls, usually unbounded recursion | Too many reachable objects |
| Time to failure | Seconds — the stack is small and fixed | Hours or days of steady growth |
| The stack trace | Thousands of identical frames | Ordinary, and at whatever line asked for memory |
| First thing to check | The base case of a recursive method | What is holding references it no longer needs |
static int countdown(int n) {
return countdown(n - 1);
}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.