3

Java doesn't have a predefined recursion depth limit. As a result the recursion below (a dummy method that returns the value) throws java.lang.StackOverflowError after 62844 (with static) and 14002 (without static) iterations.

public static int testRecursion(int number) {
    if (number == 1) {
        return 1;
    } else {
        int result = 1 + testRecursion(number - 1);
        return result;
    }    
}


public int testIteration(int number){
int result = 0;
while (number > 0){
     result++;
     number--;
     }
return result;
}

I have two concerns:

  1. Iteration method works correctly for all positive int values, whereas recursion throws an exception
  2. Changes to a method change the recursion depth at which the exception will be thrown.

Recursion in Java seems like a way to add floating bugs. Recursion depth is greater than a magic number? Program throws exception. Author modified recursive method - allowed recursion depth decreased and an exception is thrown again.

Recursions are widely used in Java. Does it mean that recursion limit is rarely reached in practical situations? Or are there some general and robust methods to deal with floating recursion depth limit?


I've read these questions:

But none of those questions discuss a problem of recursion depth in Java.

1 Answers1

8

Recursion limit hits are indicated by corresponding messages and a recursion can easily be rewritten as iterations. This makes detection and fix easy.

Recursions are typically used in situations where the recursion depth is low. As Ordous pointed out -Xss parameter can be tuned to address borderline cases.

Deep recursive calls should be avoided. Tight loops are not really suited for recursive calls.

Jowan
  • 104