Search code examples
javastack-overflow

How to avoid StackOverflowError for a recursive function


I'm writing a function that will call itself up to about 5000 times. Ofcourse, I get a StackOverflowError. Is there any way that I can rewrite this code in a fairly simple way?:

void checkBlocks(Block b, int amm) {

    //Stuff that might issue a return call

    Block blockDown = (Block) b.getRelative(BlockFace.DOWN);
    if (condition) 
        checkBlocks(blockDown, amm);


    Block blockUp = (Block) b.getRelative(BlockFace.UP);
    if (condition) 
        checkBlocks(blockUp, amm);

    //Same code 4 more times for each side

}

By the way, what is the limitation of how deep we may call the functions?


Solution

  • Use an explicit stack of objects and a loop, rather than the call stack and recursion:

    void checkBlocks(Block b, int amm) {
      Stack<Block> blocks = new Stack<Block>();
      blocks.push(b);
      while (!blocks.isEmpty()) {
        b = blocks.pop();
        Block blockDown = (Block) b.getRelative(BlockFace.DOWN);
        if (condition)
          blocks.push(block);
        Block blockUp = (Block) b.getRelative(BlockFace.UP);
        if (condition) 
          blocks.push(block);
      }
    }