When/why to call System.out.flush() in Java
JavaJava Problem Overview
Why do certain streams need to be flushed (FileOutputStream
and streams from Sockets) while the standard output stream does not?
Every time someone uses the System.out
PrintStream
object, be it while calling println()
or write()
, they never flush the stream. However, other programmers habitually call flush()
a PrintStream
/PrintWriter
with other streams.
I've recently asked this question to several programmers and some believe that there is some background handling in Java to auto-flush the System.out
stream but I can't find any documentation on that.
Something like this makes me wonder if simply calling System.out.println()
is platform independent as some systems may need you to flush the stream.
Java Solutions
Solution 1 - Java
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 - Java
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 - Java
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 - Java
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.