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.
In Java, I noticed that sometimes, System.err statements get printed first before System.out statements,
Share
Typically,
System.outis 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 forSystem.err:(My emphasis)
However, as a result, old data sent to
System.outmight show up after newerSystem.errmessages, since the old buffered data is flushed later than the message was sent toSystem.err. For example this sequence of events:System.outSystem.errand is printed immediately.System.out, and the buffered data is printedWould result in the output
Even though
Hellowas printed toSystem.outbeforePANICwas printed toSystem.err.Hope this helps!