Will Java's System.out.print() buffer forever until println()?
Asked Answered
B

1

7

I overheard an argument about System.out.print() today. One person claimed that since print() doesn't including the terminating \n, the buffer it writes to will eventually fill up and start losing data. The other person claimed that they had been using System.out.print() for all their Java programs and had never run into this issue.

Is the first person right? Is it possible for System.out.print() to start blocking or dropping data if stdout is full? Is there an example of code that will cause this?

Biparous answered 22/2, 2012 at 20:37 Comment(2)
Use System.setOut() to replace System.out with a custom stream that throws an exceptionMcdaniels
they are both wrong. the \n has nothing to do with it, calling .close() or .flush() has everything to do with contents of a stream being written out or being lost.Manuelmanuela
F
12

When the buffer used by System.out.print fills up, the output is written into the file (or terminal or other data target that is connected to the program's standard output stream), resulting in an empty buffer. Writing output without caring about the buffer size is normal usage. You will never crash or block your program or lose data from not calling flush.

You only need to call flush explicitly if you need to make the data available outside your program immediately. For example, if your program is exchanging data back and forth with another program, and you're sending a request to that program and will wait for that program's reply, you need to call flush after sending your request to ensure that the other program receives it. Similarly, if your program (or the machine it runs on) crashes, only the output up to the last time you called flush is guaranteed to have been written out.

If the stream is set to flush automatically, then writing a newline character (explicitly or through println) is as good as calling flush. Calling close also calls flush (that's why close can throw an IOException: it might have to write data out and not be able to, e.g. because the stream is connected to a file on a full disk).

Note that flushing the buffer may cause the program to block, if the stream that System.out is connected to is not immediately ready to receive the data (e.g. when the data is piped to another program that doesn't read its input immediately). Since the buffer can be flushed at any time (because the buffer happens to be full), any call to print with a non-empty argument is potentially blocking.

For more information, see the buffered streams tutorial and the documentation of the java.io.PrintStream class.

Finer answered 23/2, 2012 at 13:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.