在Java中设置最大递归深度 [英] Set maximum recursion depth in java

查看:1382
本文介绍了在Java中设置最大递归深度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经通过多种方法得到了解答:

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

  • 设置最大堆栈大小(-Xss20m)
  • 避免这种测试-如果您需要更大的递归,则问题出在程序内.
  • Set maximum stack size (-Xss20m)
  • Avoid the test what so ever - if you need a bigger recursion the problem is within the program.

这些方法很棒,但是我知道,我的代码中有问题,我想专门限制(以少量为例,例如5)递归深度,以测试这是否是递归深度问题.
有没有一种方法,例如python中的sys.setrecursionlimit?

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?

推荐答案

创建此类:

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;
        }
    }
}

然后导入static并将emerge()调用插入到代码中可以进行深度递归的任何方法的开头.您可以通过maxLevel变量来调整允许的最大递归级别. emerge()过程将以大于该变量值的级别中断执行.您可以通过将maxLevel设置为0来关闭此行为.此解决方案是线程安全的,因为它根本不使用任何计数器.

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.

这篇关于在Java中设置最大递归深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆