Oct 16, 2010

Never flush() the stream if you don't need to.

Today I found a problem that flush() the stream too often can cause freezing to the ethernet card. The computer won't have access to any network anymore. It happens to only Windows XP though. It seems like Windows 7 fixes this problem with another layer of flushing.

Here is some flushing practice I have found on the internet:

The only time you need to call flush() is if ALL of the following are true:

- You've written some of the data

AND

- You're not totally done. There's still more data to write.

AND

- You want to make sure the data you've already written reaches its destination ASAP. It is not acceptable if there's still some sitting in the buffer that goes with the next write that will come later.

Otherwise, there's no need to call it. If you're already done writing, you'll call close(), and that will call flush() anyway. If you're writing all of the data in chunks one right after the other, and not stopping to do other processing between chunks, then you'll be writing as fast as possible and calling close() right away anyway, so, again, no benefit to calling flush.

So with this code, there's no reason to call flush() explicitly. Note, however, that you should always close streams in a finally block, so that they get closed even if there's an exception.

-------------------------------------------------------------------------------

There will be no buffer overflow because OS will handle that itself. A little bit of lesson here is not to try to handle what OS has already handled; It might cause some strange problems...