了解Java堆栈 [英] Understanding the Java stack
问题描述
有以下代码:
public class Main {
public static void main(final String[] args) throws Exception {
System.out.print("1");
doAnything();
System.out.println("2");
}
private static void doAnything() {
try {
doAnything();
} catch (final Error e) {
System.out.print("y");
}
}
}
还有输出:
1yyyyyyyy2
为什么打印y八次而不再打印。遇到 StackOverflowError
时,Java如何调用 println()
Why does it print "y" eight times and no more. How can Java call println()
when StackOverflowError
encountered?
推荐答案
这里您正在捕捉错误
而不是异常
在这种情况下,您的程序会崩溃。
Here you are catching Error
and not Exception
in which case your program would have crashed.
如果您尝试此代码(修改为添加静态计数器)
If you try this code (modified to add a static counter)
public class StackError {
static int i = 1;
public static void main(final String[] args) throws Exception {
System.out.print("1");
doAnything();
System.out.println("2");
}
private static void doAnything() {
try {
i++;
// System.out.println(i);
doAnything();
} catch (Error e) {
System.out.print("y"+i+"-");
}
}
}
输出
Output
1y6869-2
所以,它有 stackerror
6869次(不同运行的更改),并打印最后一个值。如果您刚才像以前那样打印 y
,那么输出可能会缓冲并且不会被刷新,因为它不是 println
。
So, it has got stackerror
6869 times(changes for different runs) and the last value is printed. If you just print the y
as you did earlier then it might the case that the output is getting bufferred and not getting flushed as it is not a println
.
System.out.println
内部调用缓冲的 PrintStream
。您不会从缓冲区中松开任何数据,它会在填满之后或当您显式调用flush时将其全部写入输出(在您的情况下为终端)。
The System.out.println
internally calls the PrintStream
which is buffered. You don't loose any data from the buffer, it gets all written to the output( terminal in your case) after it fills up, or when you explicitly call flush on it.
回到这种情况,这取决于堆栈填充多少的内部动态,以及在 doAnything()
,并将这些字符数写入缓冲区。在主要的背面,它最后得到的打印数字 2
。
Coming back to this scenario, it depends on the internal dynamics of how much the stack is filled up and how many print statements were able to get executed from the catch in doAnything()
and those number of characters were written to the buffer. In the main back it finnally get's printed with the number 2
.
这篇关于了解Java堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!