Video in progress

What does the flush() method do, and when should you call it?

flush() forces data sitting in the buffer, not yet written, down to the underlying stream (file, socket). close() flushes by itself, so a separate call is only needed when you keep the stream open and the data has to arrive now.

📖 Answer

BufferedWriter doesn't go to disk on every write(): it collects until 8 KB is full. That is fast, but for a while the data sits only in memory.

Cases where you need a flush:

  • you sent a request through a socket and are waiting for the response: if you don't flush, the request stays in the buffer and both sides freeze waiting for each other;
  • a long-running process writes progress to a file and another program reads it;
  • an interactive console program.
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println("PING");
out.flush(); // otherwise the server receives nothing

One confusion: flush() hands data to the OS, not to the disk. The OS may hold it in its own cache. If the data must survive a power outage, you need FileChannel.force(true) or FileDescriptor.sync().