There is a deep recursion tool (with risks for the stack to explode) if the method argument cannot be resolved immediately. That is, the final result of the called method depends on the result of the method itself. Pseudo:
Result process(Parent parent) { Result result = new Result(); for (Child child : parent.getChildren()) { result.update(process(child)); } return result; }
This makes the code wait with update() until the result is known, and therefore it will be stored on the stack. And it accumulates with every method call.
You can optimize it to use tail recursion instead with a mutable result object as an argument:
void process(Parent parent, Result result) { for (Child child : parent.getChildren()) { result.update(child); process(child, result); } }
Thus, update() can be executed immediately, since the argument can be resolved immediately. As long as there is no return or any other logic after calling process() , the runtime can optimize it by dropping the call from the stack. Also see Article a wap-wiki on tail recursion and this website .
However .. The code you posted seems to be tail-recursive already. So the problem lies elsewhere. Having studied your code, you look as if you are repeating all the same children every time. That is, it is simply a means of an endless cycle. The if check is probably fictitious and / or children have backlinks in their own parent tree.
source share