Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we really need to call flush() just before close() today?

I read this question Using flush() before close() , and the accepted answer is this only means you follow the pattern.

Just like BufferedWriter#close() or FilterOutputStream.#close() , if all of buffered Stream/Writer will call its flush() when we call close() and if we (the dev and the dev who will review the code) all know the that, do we really still need this? If yes, what will be the reason?

like image 985
JaskeyLam Avatar asked Nov 11 '14 13:11

JaskeyLam


People also ask

Does Close Call flush?

Its close() method does NOT call flush() .

What are flush () and close () used for?

flush() writes the content of the buffer to the destination and makes the buffer empty for further data to store but it does not closes the stream permanently. That means you can still write some more data to the stream. But close() closes the stream permanently.

What is the use of the flush () method?

flush() method flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it.

What is the purpose of the flush () method in Java?

The flush() method of PrintWriter Class in Java is used to flush the stream. By flushing the stream, it means to clear the stream of any element that may be or maybe not inside the stream. It neither accepts any parameter nor returns any value.


1 Answers

As the javadoc says, you don't need to flush yourself. But, it's still good to do, considering your readers, and common sense.

Few experts know the javadoc by heart. I wouldn't know for sure if the stream will be flushed or not without looking it up, and I'm probably not alone. Seeing the explicit flush() call makes this perfectly clear, and therefore makes the code easier to read.

Furthermore, the method name close() implies nothing about flushing. It's from the Closeable interface, and naturally, it says nothing about flushing. If you don't flush a buffered output stream before closing, despite wanting to flush it, you'll be relying on assumptions that may or may not be true. It would weaken your implementation.

Any assumptions you make, you should somehow pass on to future maintainers. One way to do that is by leaving a comment:

// no need to flush() manually, close() will do it automatically

If you don't leave this comment, future maintainers may have to lookup the javadoc too, if like me they don't have it memorized. But then, why would you write such comment when it's easier and better to just call it yourself now and be done with it.

In short, flushing first before closing is simply following good logic. No need for assumptions and second guesses, and no need to make your readers think.

like image 70
janos Avatar answered Oct 04 '22 17:10

janos