Search code examples
javaioflush

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.


Solution

  • 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