Search code examples
javastack-overflow

How to handle deep recursions that ends with the java.lang.StackOverflowError


i got a programm with realy deep recursions, iam sure it has no endless loop. But after short time (1s) i get

java.lang.StackOverflowError

is there a possibility to increase the time that he trys to end the programm? I would like to run it a few hours if possible ;-)


Solution

  • To further the comments about reducing recursion/changing to an iterative pattern, and example may be useful. If we take the factorial function as an example, it can be written recursively (and often is) like this:

    int recurse(int n){
        if(n = 0) return 1;
        else return n*recurse(n-1);
    }
    

    however, it could be done iteratively (and therefore avoid producing stack overflows for large n) like this

    int iterate(int n){
    
        int ans = 1;
        for(int i = n; i > 0; i--){
            ans *= i;
        }
        return ans;
    
    }
    

    It is probably worth doing something similar to your code to avoid the recursion (which is likely the cause of your Error) as it is (almost?) always possible to make recursion iterative