flush() and When to Use It
You'll learn when and why to explicitly call flush() on buffered output streams to force data to disk immediately.
When you write to a BufferedOutputStream, your data sits in memory inside an internal buffer (typically 8KB). The stream only writes to disk when the buffer fills up or when you close the stream. But what if you need that data written right now—before the buffer is full and before closing?
The flush() Method
The flush() method forces any buffered data to be written to the underlying stream immediately. Think of it like this: you're filling a bucket (the buffer) to carry water to a tank (the file). Normally, you wait until the bucket is full before making the trip. But sometimes you need to pour out whatever's in the bucket now, even if it's only half-full.
When to Use flush()
Critical checkpoints: When writing log files, you might want to flush after every critical error message so the information is preserved even if your program crashes immediately after.
Interactive applications: If you're writing a network protocol or chat application, you flush to send data promptly rather than waiting for the buffer to fill.
Coordinating with other processes: If another program is reading the file you're writing, flushing ensures they see your latest updates.
Before long operations: Flush before starting a lengthy computation so partial results are saved.
When NOT to Flush
Don't flush after every single write in a loop—that defeats the entire purpose of buffering and kills performance. The buffer exists to batch writes efficiently.
Key Takeaway: Call flush() explicitly when you need to guarantee data reaches disk immediately for reliability or coordination, but avoid overusing it in performance-critical code where buffering provides significant benefits.