java 最大递归深度,在Java中设置最大递归深度

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

Set maximum stack size (-Xss20m)

Avoid the test what so ever - if you need a bigger recursion the problem is within the program.

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值