DsCpp
DsCpp

Reputation: 2489

Set maximum recursion depth in java

I know this question has been answered already via numerous methods:

Those methods are great, but I know there is a problem in my code, and I want to specifically limit (to a small number e.g. 5) the recursion depth, to test whether this is the problem.
Is there a method, like the sys.setrecursionlimit in python?

Upvotes: 5

Views: 10815

Answers (2)

John McClane
John McClane

Reputation: 3568

Create this class:

public class RecursionLimiter {
    public static int maxLevel = 10;

    public static void emerge() {
        if (maxLevel == 0)
            return;
        try {
            throw new IllegalStateException("Too deep, emerging");
        } catch (IllegalStateException e) {
            if (e.getStackTrace().length > maxLevel + 1)
                throw e;
        }
    }
}

Then import static and insert emerge() call into the beginning of any method in your code that can be deeply recursive. You can adjust maximum allowed recursion level via the maxLevel variable. The emerge() procedure will interrupt execution on a level greater than the value of that variable. You can switch off this behaviour by setting maxLevel to 0. This solution is thread-safe because it doesn't use any counter at all.

Upvotes: 2

Bill K
Bill K

Reputation: 62789

The least invasive "Manual" way to do this (also the most hacky) is probably to create a static variable in your class that is having the recursion issue. When you enter the recursive method use it to count the recursion depth (by adding or subtracting) and when you exit, reverse what you did upon entry.

This isn't great but it is a lot better than trying to set a stack depth (Nearly any system call in java will blow through 5 levels of stack without even blinking).

If you don't use a static you may end up having to pass your stack depth variable through quite a few classes, it's very invasive to the rest of your code.

As an alternative I suggest you let it fail "normally" and throw the exception then meditate upon the stack trace for a while--they are really informative and will probably lead you to the source of your problem more quickly than anything else.

static int maxDepth = 5;
public void recursiveMethod() {
    if(maxDepth-- == 0)
        throw new IllegalStateException("Stack Overflow");
    recursiveMethod();
    maxDepth++;
}

Upvotes: 3

Related Questions