我在这段代码上遇到了 StackOverFlowException,因为我的 JVM 不支持尾部调用优化,对吗?
我在这个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
据我所知,没有 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:
是的,由于安全模型和始终需要可用的堆栈跟踪,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.
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
我在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.