> Stack Overflow error

I have an infinite recursive loop in java

public  void infiniteLoop(Long x){

    System.out.println(""+x);
    infiniteLoop(x + 1);
}

public static void main(String[] args) {

    StackOverFlow st = new StackOverFlow();
    st.infiniteLoop(0L); 
}

In this piece of code it display an StackOverFlow error as expected, but if I look in the console output the error is displayed in multiple lines:

4806
4807
4808
    at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129)
    at java.io.PrintStream.write(PrintStream.java:526)
    at java.io.PrintStream.print(PrintStream.java:669)
    at java.io.PrintStream.println(PrintStream.java:806)
    at stackoverflow.StackOverFlow.infiniteLoop(StackOverFlow.java:234809
)
    at stackoverflow.StackOverFlow.infiniteLoop(StackOverFlow.java:24)
    at stackoverflow.StackOverFlow.infiniteLoop(StackOverFlow.java:24)
4810
4811
4812

My question is, why does this happens? shouldn't it stops as soon as the first Stack Overflow error is displayed?


[S]houldn't it stops as soon as the first Stack Overflow error is displayed?

Actually the program stops at the first stackoverflow exception. But exceptions are written to the stderr channel (so System.err.println(..) ) whereas you print output to the stdout channel.

The terminal listens to both channels and aims to print them in a good way, but since these are separate channels, there is no guarantee that the order in which the producers write to the channels is displayed correctly: the order of the individual channels is always correct, but if data is written to both channels (almost) concurrently, the streams might be mixed up a bit.

You can alter your program to print to the stderr as well:

public void infiniteLoop(Long x){
    System.err.println(""+x); // error channel.
    infiniteLoop(x + 1);
}

Now the order in which data is written to the channel should also be the order in which it is displayed on the terminal.

链接地址: http://www.djcxy.com/p/80462.html

上一篇: 另一个编码器被递归混淆

下一篇: >堆栈溢出错误