When/why to call System.out.flush() in Java

Solution 1:

System.out is based around a PrintStream which by default flushes whenever a newline is written.

From the javadoc:

autoFlush - A boolean; if true, the output buffer will be flushed whenever a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written

So the println case you mention is explicitly handled, and the write case with a byte[] is also guaranteed to flush because it falls under "whenever a byte array is written".

If you replace System.out using System.setOut and don't use an autoflushing stream, then you will have to flush it like any other stream.

Library code probably shouldn't be using System.out directly, but if it does, then it should be careful to flush because a library user might override System.out to use a non flushing stream.

Any Java program that writes binary output to System.out should be careful to flush before exit because binary output often does not include a trailing newline.

Solution 2:

From the PrintStream documentation:

Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written.

Although I don't see it mentioned explicitly in the documentation, it's my understanding that System.out will perform this auto-flushing.

Solution 3:

When you can't wait for the item to be displayed, flush the stream.

When the JVM goes down, not flushing the stream risks the item being lost in the display buffer, which might make the sensible error message telling you why the JVM went down lost forever. That makes debugging much more difficult, as people then tend to say, "but it didn't get here, because it would have printed this".

Solution 4:

System.out is by default line-buffered. So if you are calling println and not print it should not be a problem. See this article for more info.