In Java, I noticed that sometimes, System.err
statements get printed first before System.out
statements, although the latter appears first before the former in my code. Why? I'm curious.
Typically, System.out
is a buffered output stream, so text is accumulated before it is flushed to the destination location. This can dramatically improve performance in applications that print large amounts of text, since it minimizes the number of expensive system calls that have to be made. However, it means that text is not always displayed immediately, and may be printed out much later than it was written.
System.err
, on the other hand, typically is not buffered because error messages need to get printed immediately. This is slower, but the intuition is that error messages may be time-critical and so the program slowdown may be justified. According to the Javadoc for System.err
:
Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored.
(My emphasis)
However, as a result, old data sent to System.out
might show up after newer System.err
messages, since the old buffered data is flushed later than the message was sent to System.err
. For example this sequence of events:
System.out
System.err
and is printed immediately.System.out
, and the buffered data is printedWould result in the output
PANIC
Hello, world!
Even though Hello
was printed to System.out
before PANIC
was printed to System.err
.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With