gpt4 book ai didi

java - 递归调用期间发生 StackOverflowError

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:11:02 26 4
gpt4 key购买 nike

这个问题完全是理论上的,但我找不到答案。考虑这个短程序:

public class SBtst {

int i = 0;

public static void main(String[] args) {
new SBtst().rec();
}

public void rec() {
System.out.println("rec is called "+i++);
try {
rec();
} catch (StackOverflowError soe) {
System.out.println("completed "+soe.getStackTrace().length);
}
}

}

执行后我得到类似的输出:

rec is called 10472
rec is called 10473
rec is called 10474Recursion completed 1024

问题是:

  1. 为什么 println() 没有完成新行,因为据我了解,当执行下一个 rec() 调用时应该抛出一个错误,它是在 println() 完成之后

    <
  2. 为什么我在 stackTrace 数组中只得到 1024 个元素,而 i 却等于 10474?这是否意味着并非每个调用都在堆栈跟踪中?

最佳答案

为什么异常显然是从 println 中抛出的?

Why didn't println() complete a new line? As I understand, the exception should be thrown when the next rec() call is executed, but that would be after println() has completed.

你的理解不太正确。在某些时候,堆栈看起来像:


rec()
rec()
rec()
println()

Println 也会消耗资源(请参阅 mattingly890's answer ),并且没有理由在此时无法达到限制。

为什么堆栈跟踪包含的帧数少于实际使用的帧数?

Why do I get only 1024 elements in the stack trace, even though at least 10474 were used? Does it mean that not every call is in the stack trace?

查看 getStackTrace() 的文档:

Provides programmatic access to the stack trace information printed by printStackTrace(). Returns an array of stack trace elements, each representing one stack frame. The zeroth element of the array (assuming the array's length is non-zero) represents the top of the stack, which is the last method invocation in the sequence. Typically, this is the point at which this throwable was created and thrown. The last element of the array (assuming the array's length is non-zero) represents the bottom of the stack, which is the first method invocation in the sequence.

Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this throwable is permitted to return a zero-length array from this method. Generally speaking, the array returned by this method will contain one element for every frame that would be printed by printStackTrace. Writes to the returned array do not affect future calls to this method.

评论中Peter Lawrey found the documentation其中提到了堆栈大小的 1024 默认限制:

Java HotSpot VM Options

-XX:ThreadStackSize=512

Thread Stack Size (in Kbytes). (0 means use default stack size) [Sparc: 512; Solaris x86: 320 (was 256 prior in 5.0 and earlier); Sparc 64 bit: 1024; Linux amd64: 1024 (was 0 in 5.0 and earlier); all others 0.]

不过,可能还有其他因素在起作用。例如,这些问题提到了另外两个选项:

关于java - 递归调用期间发生 StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25610298/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com