递归方法的间歇性堆栈溢出 [英] Intermittent Stack Overflow for Recursion Method

查看:47
本文介绍了递归方法的间歇性堆栈溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为课堂作业编写了一个简单的方法,该方法使用递归(是的,它必须使用递归)来计算分形图案中的三角形数量:

I have a simple method I've written for a class homework assignment that uses recursion (yes, it must use recursion) to calculate the number of triangles in a fractal pattern:

public static BigInteger triangleFract(int layer) {
    if(layer < 0) {
        throw new IllegalArgumentException("Input must be >= 0");
    } else if(layer == 0) {
        return new BigInteger("0");
    } else if (layer == 1) {
        return new BigInteger("1");
    } else {
        return triangleFract(layer - 1)
              .multiply(new BigInteger("3"))
              .add(new BigInteger("2"));
    }
}

我一直试图做的是了解 int 层可以有多大以限制用户输入.经过一些测试后,堆栈溢出大约 6700+,这很好.

What I've been trying to do is understand how big the int layer can be so as to limit user input. After some tests I get a stack overflow at around 6700+, which is fine.

困扰我的是,如果层数在数千,该方法通常会运行,但它仍然会随机遇到StackOverflowError.

What is troubling me is that if layer is in the thousands, the method usually runs, but it can still randomly encounter a StackOverflowError.

例如,我选择将 layer 限制为 4444,它似乎几乎总是能够处理,但每隔一段时间它似乎仍然溢出.

For instance, I chose to limit layer to 4444, and it seems to be able to handle that almost always, but every once in a while it still seems to overflow.

为什么要这样做?有什么我可以做的吗?

Why does it do this? And is there anything that I can do about it?

推荐答案

也许 JVM 已经确定(通过转义分析)BigInteger 可以在堆栈上而不是堆上分配.根据它何时实现此优化,所需的堆栈大小会有所不同.

Perhaps the JVM has determined (through escape analysis) that the BigInteger can be allocated on the stack rather than the heap. Depending on when it implements this optimization, the required stack size would vary.

也就是说,可能有许多其他原因,行为可能取决于您使用的 JVM.

That said, there could be many other causes, and the behaviour is likely to depend on the JVM you use.

这篇关于递归方法的间歇性堆栈溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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