Video in progress

Strong Middle 🧠 Problem solving

In production, a recursive tree traversal started throwing StackOverflowError on large data. What do you do?

First I confirm the cause: I look in the stack trace for one method repeated thousands of times and check the depth of the data. Then I move the recursion onto an explicit stack with ArrayDeque. Raising -Xss is only a temporary patch.

📖 Answer

A typical scenario: a category tree or a chain of comments is built through parent_id and walked recursively. In tests the depth is 5-10; on prod someone has created a chain 20,000 levels deep, or the data has a cycle (A → B → A), in which case the depth is unbounded.

So the first question is: is this really a deep tree or a cycle? If it's a cycle, enlarging the stack doesn't help; you need a visited set.

Replacing the recursion with a loop:

static long sumTree(Category root) {
    long total = 0;
    Deque<Category> stack = new ArrayDeque<>();
    Set<Long> seen = new HashSet<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        Category c = stack.pop();
        if (!seen.add(c.id())) continue;      // protection against cycles
        total += c.amount();
        for (Category ch : c.children()) stack.push(ch);
    }
    return total;
}

Now the depth is limited by the heap, not the stack, and the heap is hundreds of times bigger.

About -Xss: it enlarges the stack for every thread. In a service with hundreds of threads that takes a noticeable amount of memory and only postpones the problem until the next, larger data set. If you really must, you can start a thread with its own stack size just for that job, like new Thread(null, task, "deep", 64L << 20).

If you need postorder (children first, then the parent), the iterative version is more complicated: you push a node onto the stack twice, or keep a "children processed" flag. And so it doesn't come back, write a unit test with a deep-chain test data set.