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.
问题:
回答1:
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!
回答2:
It has to do with buffering and priority. Presumably, Java (like C and C-derivatives) does not buffer System.err
, stderr
, etc., unlike System.out
, stdout
, etc. This way, the system can ensure that you'll most likely get any relevant error messages, even if it has to drop standard output for one reason or other.
From Wikipedia:
It is acceptable—and normal—for standard output and standard error to be directed to the same destination, such as the text terminal. Messages appear in the same order as the program writes them, unless buffering is involved. (For example, a common situation is when the standard error stream is unbuffered but the standard output stream is line-buffered; in this case, text written to standard error later may appear on the terminal earlier, if the standard output stream's buffer is not yet full.)