krystah
krystah

Reputation: 3733

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 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.

Upvotes: 7

Views: 1776

Answers (3)

Ferrybig
Ferrybig

Reputation: 18834

This is needed when using either ObjectInputStream and ObjectOutputStream, because they send a header over the stream before the first write is called. The call to flush() will send that header to the remote side.

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

magic version

If the header doesn't arrive at the moment a ObjectInputStream is build, this call will hang until it received the header bytes.

This means that if the protocol in question is written with ObjectStreams, it should flush after creating a ObjectOutputStream.

Note that this practice is only required when using the ObjectOutputStream to send to a real time viewer. If writing it to an file, it isn't typically needed

Upvotes: 3

jwenting
jwenting

Reputation: 5663

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?

Upvotes: 2

Saurabh Jain
Saurabh Jain

Reputation: 1712

When you write data out to a stream, some amount of buffering will occur, and you never know for sure exactly when the last of the data will actually be sent. You might perform many rite operations on a stream before closing it, and invoking the flush()method guarantees that the last of the data you thought you had already written actually gets out to the file. Whenever you're done using a file, either reading it or writing to it, you should invoke the close()method. When you are doing file I/O you're using expensive and limited operating system resources, and so when you're done, invoking close()will free up those resources.

Upvotes: 1

Related Questions