ObjectOutputStream.flush() and Stream Flushing
What you'll learn: You'll discover when and why to explicitly flush an ObjectOutputStream to guarantee your serialized data actually gets written out.
The Buffering Problem
When you write objects using ObjectOutputStream, the data doesn't necessarily go straight to the destination (file, network socket, etc.) immediately. Instead, it's often held in an internal buffer—a temporary holding area in memory—to improve performance. Think of it like filling a delivery truck: you don't send the truck for every single package; you wait until you have enough to make the trip worthwhile.
But what if you need that data written right now? That's where flushing comes in.
What flush() Does
Calling flush() on your ObjectOutputStream forces any buffered data to be written to the underlying stream immediately:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.ser"));
oos.writeObject(myObject);
oos.flush(); // Forces data out of buffer NOW
When to Flush
You typically need to flush when:
- You're keeping the stream open for a long time and want to ensure data is saved before continuing other operations
- You're writing to a network stream and the recipient needs the data immediately
- Before checking file contents while the stream is still open
- Before critical operations where data loss would be unacceptable
Note: Calling close() automatically flushes, so you don't need both. However, if you're not closing the stream yet, explicit flush() ensures data isn't lost if something goes wrong.
Key Takeaway: Use ObjectOutputStream.flush() to force buffered serialized data to be written immediately, especially when you need guaranteed persistence before the stream closes or when coordinating with other processes that need the data right away.