Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it necessary to flush the output buffer when it was just created?

Tags:

java

io

flush

In the following scenario

ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
output.flush();
// Do stuff with it

Why is it always necessary to flush the buffer after initial creation?
I see this all the time and I don't really understand what has to be flushed. I kind of expect newly created variables to be empty unless otherwise is specified.

Kind of like buying a trash-can and finding a tiny pile of trash inside that came with it.

like image 414
krystah Avatar asked Mar 03 '14 11:03

krystah


People also ask

Why do you need to flush the buffer?

The buffer flush is used to transfer of computer data from one temporary storage area to computers permanent memory. If we change anything in some file, the changes we see on the screen are stored temporarily in a buffer. In C++, we can explicitly have flushed to force the buffer to be written.

What does it mean to flush the output buffer?

Flushing output on a buffered stream means transmitting all accumulated characters to the file. There are many circumstances when buffered output on a stream is flushed automatically: When you try to do output and the output buffer is full.

Why is it important to flush the output stream of a socket after writing data to it?

The method flush() flushes all the streams of data and executes them completely giving a new space to new streams. Flushing an output stream means that you wait for the content of the stream to be completely transferred to its destination before resuming the execution with the stream empty and the content sent.

What is the purpose of a flush function?

C++ manipulator flush is used to synchronize the associated stream buffer with its controlled output sequence. For the stream buffer, objects that implement intermediate buffers, flush function is used to request all characters written to the controlled sequence.


1 Answers

In over 15 years of writing Java on a professional level I've never once encountered a need to flush a stream before writing to it.
The flush operation would do nothing at all, as there's nothing to flush.
You want to flush the stream before closing it, though the close operation should do that for you it is often considered best practice to do it explicitly (and I have encountered situations where that did make a difference, where apparently the close operation did not actually do a flush first.
Maybe you are confused with that?

like image 89
jwenting Avatar answered Sep 29 '22 04:09

jwenting