Will there be a Java System.out.print () buffer forever before println ()?

Today I heard an argument about System.out.print() . One person claimed that since print() does not include the trailing \n , the buffer that it writes will eventually fill up and begin to lose data. Another person claimed that they used System.out.print() for all of their Java programs and never encountered this problem.

Is the first person right? Is it possible for System.out.print() start blocking or deleting data if stdout is full? Is there any sample code that will call this?

+6
source share
1 answer

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.

+11
source

Source: https://habr.com/ru/post/909126/


All Articles