When the buffer used by System.out.print
is System.out.print
, the output is written to a file (or a terminal or other data object connected to the standard output of the program), resulting in an empty buffer. Writing output without regard to buffer size is normal use. You will never crash or block your program or lose data without causing flush
.
You only need to explicitly call flush
if you need to immediately make the data available outside your program. For example, if your program is exchanging data with another program, and you send a request for this program and wait for the response of this program, you need to call flush
after sending the request to make sure that another program is receiving it. Similarly, if your program (or the machine it is running on) crashes, it is guaranteed that only the output signal will be written out until the last flush
call.
If the thread is configured to automatically shut down, then writing a newline (explicitly or via println
) is as good as calling flush
. The close
call also calls flush
(therefore, close
can cause an IOException
: it may have to write data and not be able to, for example, because the stream is connected to a file on a full disk).
Please note that clearing the buffer can lead to blocking the program if the stream to which System.out
connected is not immediately ready to receive data (for example, when data is transferred to another program that does not read its input immediately). Since the buffer can be flushed at any time (because the buffer is full), any call to print
with a non-empty argument potentially blocks.
See the buffered stream tutorial and the java.io.PrintStream
documentation for more information.
source share