Fix StackOverflowError in Recursive Java Code and Loops
Fix java.lang.StackOverflowError by finding the missing base case or the hidden cycle, then convert deep recursion to a loop or raise the thread stack size.

A StackOverflowError means a thread has used up its call stack. Each method call adds a frame, and when the frames no longer fit, the JVM throws. In nearly every case the cause is recursion that does not stop: a base case that is wrong, or two methods that call each other forever. The error comes with a stack trace of thousands of nearly identical lines, which looks intimidating and contains the answer in its first dozen. This post shows how to read the trace, covers the three causes in order of likelihood, and says when raising the stack size is justified. It applies to Java 25.
Exception in thread "main" java.lang.StackOverflowError
at dev.javahacks.Tree.depth(Tree.java:14)
at dev.javahacks.Tree.depth(Tree.java:14)
at dev.javahacks.Tree.depth(Tree.java:14)
... (repeats)Read the first few lines and the last few. The repeating frames are the loop, and the line number tells you which call makes it. The frames at the bottom show how the program got into the loop. The JVM truncates the trace at 1,024 frames by default, so you see the top of the stack, which is the useful end for this error.
Cause 1: the base case is missing or unreachable
static int factorial(int n) {
return n * factorial(n - 1); // never stops
}Every recursive function needs a condition under which it returns without calling itself, and each call must move towards that condition. Here there is no condition at all. Add it:
static long factorial(int n) {
if (n < 0) throw new IllegalArgumentException("n must not be negative: " + n);
if (n <= 1) return 1;
return n * factorial(n - 1);
}Subtler versions have a base case that is never reached, such as n == 0 when the input can be negative, or a recursion on a copy that is not smaller. A check on n == 0 with factorial(-1) descends through -2, -3 and so on until the stack ends. Using <= and validating the input removes the hole. When you suspect a base case, test the smallest and the invalid inputs first.
Cause 2: a cycle of object references
The recursion is sometimes hidden in code you did not write as a loop. Two objects that refer to each other and a method that walks references create one:
class Customer {
List<Order> orders = new ArrayList<>();
@Override public String toString() { return "Customer" + orders; }
}
class Order {
Customer customer;
@Override public String toString() { return "Order" + customer; }
}Printing a customer calls toString on its orders, each of which calls it on the customer, forever. The same shape appears in equals, hashCode, JSON serialisation and object copying whenever the object graph has a cycle. The JSON case is common in applications with bidirectional JPA mappings and is solved in Jackson infinite recursion. The fix is to break the cycle in the method that walks it: print only the order ids from Customer.toString, or leave the back reference out of Order.toString. Do the same in generated methods from Lombok or an IDE by excluding the back reference.
Cause 3: the input really is deep
Sometimes the recursion is correct and the data is deep. A recursive walk over a linked list of 100,000 nodes, a depth-first search of a long chain, a parser on deeply nested input or a naive recursive Fibonacci on a large argument can all exhaust a 1 MB stack even though each call is right. The cure is to turn the recursion into a loop with an explicit stack, which lives on the heap and grows as needed:
static int depth(Node root) {
int max = 0;
Deque<Node> nodes = new ArrayDeque<>();
Deque<Integer> levels = new ArrayDeque<>();
nodes.push(root); levels.push(1);
while (!nodes.isEmpty()) {
Node node = nodes.pop();
int level = levels.pop();
max = Math.max(max, level);
for (Node child : node.children()) {
nodes.push(child);
levels.push(level + 1);
}
}
return max;
}Java does not optimise tail calls, so rewriting a recursive method in tail form does not help; the loop is the answer. Regular expressions are a special case. Some patterns with nested repetition recurse inside the engine, and a long input produces a StackOverflowError from java.util.regex. Simplify the pattern or avoid regular expressions on large inputs.
Raising the stack size
java -Xss4m -jar app.jar-Xss sets the stack size of new threads; the default on 64-bit platforms is typically one megabyte. Raising it lets a legitimately deep recursion finish, and it is the last resort: it hides an infinite recursion for a few extra seconds and costs memory for every thread. With 500 threads at 4 MB each, the reserved stack is 2 GB of address space. To give one thread a large stack without changing every thread, create it with the size you need:
Thread worker = new Thread(null, task, "deep-walk", 64L * 1024 * 1024);
worker.start();Use that for a known, bounded workload such as a parser for trusted input, and not as a patch for a recursion you do not understand. How the stack relates to other memory areas is explained in JVM memory areas, and how to read the traces in reading a stack trace.
Finding the recursion in a big codebase
When the repeating frames are inside a framework, the loop is rarely in the framework. Scroll to the first frame in your own package: that method, or the one just below it, closes the loop. Typical shapes are a Jackson serialiser walking a cyclic graph, a Hibernate toString that prints a lazy collection, a Spring bean whose constructor depends on itself through a proxy, and a logging call that formats an object whose toString logs. Take a thread dump or a debugger snapshot at the moment of the error and read the distinct method names, ignoring repeats. Two or three names that repeat in order are the cycle.
Then write a test that reproduces it with the smallest input, such as two objects pointing at each other, assert that it no longer throws after the fix, and keep it. A recursion bug that returned once will return when someone adds a new association.
Tail calls, memoisation and depth
Recursion that is legitimately deep sometimes has a different problem: it is also slow. A naive recursive Fibonacci recomputes the same values exponentially often. Memoise the results in a map, or convert to a loop, and the depth and the time both fall. For tree and graph walks, an iterative traversal with an explicit stack uses heap memory proportional to the width, not the call stack, and is easier to pause, limit and instrument. Add a depth limit when the data comes from outside, and fail with a clear error when it is exceeded, for example in a parser: a 10,000-deep nested JSON document sent by a hostile client should be rejected, not allowed to crash a thread.
Where this does not apply
A StackOverflowError is not an OutOfMemoryError. If the message mentions heap space, look at heap space errors instead. Catching StackOverflowError to continue is rarely wise, as the state of the thread's work is unknown. The class is documented in the [StackOverflowError Javadoc](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/StackOverflowError.html), and the -Xss option in the [java command reference](https://docs.oracle.com/en/java/javase/25/docs/specs/man/java.html).


