Video in progress

When does a StackOverflowError appear, and how do you track it down?

When a thread's stack fills up, usually in recursion that never ends or goes very deep. In the stack trace the same methods repeat over and over, and the repeating part points to the cause.

📖 Answer

The most common causes:

  • the recursion has no stop condition, or a wrong one;
  • two objects call each other's toString()/hashCode();
  • turning a bidirectionally linked entity into JSON with Jackson;
  • very deep but correct recursion (for example, walking a linked list of 100 thousand elements recursively).
int factorial(int n) {
    return n * factorial(n - 1); // doesn't stop at n == 0
}

How to find it: open the stack trace in the log; the same 2-3 lines repeat hundreds of times. That cycle is the cause.

The fix is to correct the logic first (the stop condition, @ToString.Exclude, @JsonIgnore). If the recursion is really deep, turn it into a loop or your own Deque stack. Increasing -Xss is a temporary patch, and it raises the memory of every thread.