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

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 the initial creation?
I see this all the time, and I really don't understand what needs to blush. I expect newly created variables to be empty unless otherwise indicated.

It seems like buying a trash can and finding the tiny pile of trash inside that came with it.

+6
source share
3 answers

This is necessary when using ObjectInputStream and ObjectOutputStream , since they send a header over the stream before the first record is called. A call to flush() will send this header to the remote side.

According to spec, the header exists from the following contents:

 magic version 

If the header does not appear at the time of assembling the ObjectInputStream, this call will hang until it receives the bytes of the header.

This means that if the corresponding protocol is written using ObjectStream s, it must be hidden after creating the ObjectOutputStream .

0
source

For more than 15 years of writing Java on a professional level, I have never encountered the need to flush a stream before writing to it.
A flush operation would not do anything because there is nothing flush.
You want to clear the thread before closing it, although the close operation should do it for you, so it’s often considered that it’s best to do it explicitly (and I came across situations where it really mattered, where, apparently, the closed operation don't actually make a flash first.
Maybe you are confused about this?

+2
source

When you write data to a stream, a certain amount of buffering will occur, and you do not know exactly when the last of the data will be sent. You can perform many ritual operations in the stream before closing it, and calling the flush () method ensures that the last of the data that you thought you already wrote actually gets into the file. Whenever you finish using a file, either by reading it or writing to it, you must call the close () method. When you perform file input / output, you use the expensive and limited resources of the operating system, so when you are done, calling the close () function will free those resources.

+1
source

All Articles