Will Java's System.out.print() buffer forever

2019-01-20 10:01发布

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?

1条回答
Summer. ? 凉城
2楼-- · 2019-01-20 10:46

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.

查看更多
登录 后发表回答