Skip to content
Latchkey

Java "java.lang.StackOverflowError" in CI - Fix Unbounded Recursion

StackOverflowError means the thread's call stack hit its limit - overwhelmingly because of recursion that never terminates or a cyclic call chain (e.g. mutual getters, serializing a bidirectional object graph). Raising the stack size hides the symptom; the cycle is the bug.

What this error means

A test or run dies with java.lang.StackOverflowError and a long, repeating stack trace showing the same frames cycling. Common around recursive algorithms, equals/hashCode loops, and JSON serialization of bidirectional relations.

java
java.lang.StackOverflowError
        at com.example.Node.toString(Node.java:14)
        at com.example.Node.toString(Node.java:14)
        at com.example.Node.toString(Node.java:14)
        ... (repeats)

Common causes

Recursion without a base case

A method calls itself (directly or via a cycle) with no terminating condition, so frames pile up until the stack is exhausted.

A serialization or equals/hashCode cycle

Bidirectional object graphs (parent<->child) serialized by Jackson, or mutually-recursive equals/toString, loop forever.

How to fix it

Fix the recursion or break the reference cycle

Add the missing base case, or annotate the back-reference so serialization does not recurse.

java
// Jackson: break the parent<->child cycle
class Parent {
  @JsonManagedReference List<Child> children;
}
class Child {
  @JsonBackReference Parent parent; // not serialized back
}

Diagnose the cycle from the trace

  1. Find the repeating frame block at the top of the stack - those methods form the loop.
  2. Add or correct the base case so the recursion terminates.
  3. Only as a last resort raise -Xss (e.g. -Xss4m); a genuine cycle will still overflow.

How to prevent it

  • Guard every recursive method with a clear base case, prefer iteration for deep structures, and annotate bidirectional models to avoid serialization cycles.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →