我在这段代码上遇到了 StackOverFlowException,因为我的 JVM 不支持尾部调用优化,对吗?

发布于 2024-10-07 08:24:13 字数 441 浏览 0 评论 0原文

我在这个 Java 方法上遇到了 StackOverflowException :

private static final Integer[] populate(final Integer[] array, final int length, final int current) {

    if (current == length) {
        return array;
    } else {
        array[current] = TR.random.nextInt();
        System.out.println(array[current]);
        return populate(array, length, current + 1);
    }
}

我正在使用尾调用递归,所以我猜这就是 JVM 没有短路堆栈时会发生的情况,对吗?

I get a StackOverflowException on this Java method:

private static final Integer[] populate(final Integer[] array, final int length, final int current) {

    if (current == length) {
        return array;
    } else {
        array[current] = TR.random.nextInt();
        System.out.println(array[current]);
        return populate(array, length, current + 1);
    }
}

I'm playing with tail call recursion so I guess this is what happens when the JVM doesn't short circuit the stack right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

抠脚大汉 2024-10-14 08:24:13

据我所知,没有 JVM 支持尾部调用优化。这并非疏忽。显然,这种优化对于 Java 反射和 Java 安全管理器具有重大影响。

参考文献:

No JVM that I'm aware of supports tail call optimization. This is not an oversight. Apparently this optimization has significant consequences for Java reflection and Java security managers.

References:

阳光下的泡沫是彩色的 2024-10-14 08:24:13

是的,由于安全模型和始终需要可用的堆栈跟踪,JVM 目前不支持尾部调用优化,不过可以使用迭代轻松重写此示例。

Yes, Tail Call Optimization is not currently supported by the JVM because of the security model and the need to always have a stack trace available, this example could easily be rewritten using iteration though.

花想c 2024-10-14 08:24:13

AFAIK,普通 Java 没有尾部调用优化。 Scala 的实现确实有些有限: http://fupeg .blogspot.com/2009/04/tail-recursion-in-scala.html

Plain Java doesn't have tail call optimization, AFAIK. Scala does have a somewhat limited implementation of it: http://fupeg.blogspot.com/2009/04/tail-recursion-in-scala.html

一曲琵琶半遮面シ 2024-10-14 08:24:13

我在java中找到了尾递归的参考,因此我会检查一下,(稍后当我有时间的时候)。

尽管这对于您的用例来说效率极低。

I found a reference of tail recursion in java, therefore I would check this, (later when I've time).

Although it would be extremly ineffiecent for your use case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文