Timing issues with PrintStreams
I'm using eclipse IDE, and sometimes, depending on the code, System.err output is printed before than System.out's. For instance:
public static void main(String[] args) {
System.out.println("Regular text")开发者_开发问答; //1
System.err.println("Error text"); //2
}
With that code, everything is fine. 2 is printed after 1. However, adding some extra system.out sentences reverses the order:
public static void main(String[] args) {
System.out.println("Regular text"); //1
System.err.println("Error text"); //2
//Additional printing stuff
for(String s = "a";s.length() < 200; s = s.concat("" + (char)(s.charAt(s.length()-1)+ 1))){
System.out.println(s);
}
}
1 is printed after 2.
How is this possible?
stderr
and stdout
are 2 different streams, and normally will be printed when flushed. I would expect some buffering to take place and this would affect flushing. Consequently the quantity of data in each stream will affect the flushing and the output.
On some OSes (*nix in particular), the standard output stream is buffered -- that is, whatever gets sent to it might sit around a bit before being sent to the terminal/screen. Standard error, however, often is not buffered, or is auto-flushed after each output.
System.out
and System.err
are just Java's objects to represent those two streams, and thus, tend to behave as they would on the host platform. But i'm not aware of anything that specifically says they have to.
They are separate streams each with their own buffers. You write to a stream which is then "copied" or written out to the console.
You should find that calling
System.out.flush()
System.err.flush()
will flush the streams to the actual device (the Eclipse console) and bring some semblance of order.
精彩评论