Why do System.err statements get printed first sometimes?

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:

  • “Hello,” is buffered to System.out
  • “PANIC” is sent directly to System.err and is printed immediately.
  • ” world!” is buffered to System.out, and the buffered data is printed

Would 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!

Leave a Comment