Question

What are the side effects of flushing a OutputStreamWriter which is going to a network socket.

I have a program which calls out.flush() after every few bytes. Is there any reason why I should wait until all bytes I need are in the buffer?

Will I get lower transfer rate if I flush too much (more overhead)?

Will this slow down execution of my program (blocking)?

Was it helpful?

Solution

Each time you write to a socket, you add between 5 and 15 micro-seconds. For buffered output, this occurs when you flush() the data. Note: if you don't have a buffered output, it will be performed on every write() and the flush() won't do anything.

Fortunately the OS expects applications to make more calls than is optimal so the it uses Nagle's algorithm by default to groups portions of the data writing into a larger packets. Note: not only does the OS do this but some network adapter do this by default too.

In short, don't flush() too often but unless tens of micros-seconds add up to something which matters to you, you might not notice the difference. e.g. if you do 100 flushes you might add a milli-second.

OTHER TIPS

There is no reason to flush unless:

  • you want the peer to receive the data as soon as possible
  • you've sent a buffered request and you're now going to read the response.

In other cases it is better to allow the buffer, the Nagle algorithm, and the TCP receive window work their magic.

In case of data transfer on network, batching of outputStreamWriter's flush does improve performance. I observed that single flush of data packet of about 520 bytes was taking around 3 milliseconds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top