Quick revision
The short answer
A BufferedWriter keeps written data in memory and only passes it to the file when its buffer fills, when flush() is called, or when it is closed. The log shipper never closes the writer before the process exits, so the last partly filled buffer, which holds the final lines, is simply thrown away. The fix is try-with-resources or a close in the shutdown path, plus flush() after important writes; a reviewer should also check how the stream chain is closed and remember that flush() does not make data durable on disk, which needs FileChannel.force.
What to remember
In this answer, we saw that a BufferedWriter only writes its buffer when it fills, on flush() or on close(), so a writer that is never closed loses its last partial buffer at exit. The fix is try-with-resources or a close in the shutdown path, with flush() after important writes. A reviewer should also check that the outermost wrapper is the one closed, that write failures are not swallowed, and that durability needs FileChannel.force, because flush only reaches the operating system.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A BufferedWriter keeps written data in memory and only passes it to the file when its buffer fills, when flush() is called, or when it is closed. The log shipper never closes the writer before the process exits, so the last partly filled buffer, which holds the final lines, is simply thrown away. The fix is try-with-resources or a close in the shutdown path, plus flush() after important writes; a reviewer should also check how the stream chain is closed and remember that flush() does not make data durable on disk, which needs FileChannel.force.
Background to this question
Missing the last lines of a file is a classic symptom, and in a log shipper it is a serious one: the lines just before a crash or a shutdown are usually the most important. The cause is simple once we see it, but the review around it is where seniority shows, because buffering, closing order, shutdown hooks and durability are four different layers that people often merge into one. In this answer, we will recap how a BufferedWriter holds data, reproduce the lost lines, fix them properly, and then walk through the other things a reviewer should check, ending with the difference between flushed and durable.
1A Quick Recap of How BufferedWriter Holds Data
BufferedWriter wraps another Writer, usually one that writes to a file. Instead of passing every write straight through, it collects characters in an internal char array, 8,192 chars by default. Writing to an array is cheap, and passing data on in large blocks means far fewer system calls, which is the whole point of buffering.
The data in that array leaves it at only three moments: when the array is full and a new write needs room, when we call flush(), and when we call close(), which flushes and then closes the underlying writer. Until one of those happens, the lines exist only in the JVM's memory. If the JVM exits first, they are gone.
- BufferedWriter's char arraylost if the JVM exits without flush or close
- Encoder and FileOutputStream
flush()pushes data down to here and into the OS - OS page cachesurvives a JVM exit, lost on power failure or kernel crash
- Diskdurable only after
force()or fsync
4 layers, from the top down. Step through them one at a time.
flush() moves data from the top layer to the OS; only force or fsync reaches the bottom.
2Reproducing the Lost Lines
A simplified shipper might open a writer when it starts and write each line as it arrives. Nothing closes the writer, because the developer expected the process exit to take care of it.
The lines reach the file only in large blocks, each time a buffer fills. There are in fact two buffers here: Files.newBufferedWriter puts a BufferedWriter, which buffers chars, on top of an encoder that keeps its own buffer of bytes, so how much reaches the file before exit depends on both. Whatever is still in either buffer when System.exit runs is lost. Java does not flush or close open writers on exit, because it has no idea which objects are writers or in what order they should be closed. So the file stops at a block boundary, which is exactly the pattern of missing last lines in each file.
3The Fix: Close It, and Flush When It Matters
When the writer has a clear scope, such as writing one file, try-with-resources closes it automatically, which flushes the buffer, even if an exception is thrown in the middle.
A shipper that keeps a writer open for its whole life needs a close on the shutdown path instead. In a Spring application we close it in a @PreDestroy method or a bean destroy method, which runs on a graceful shutdown; in plain Java we register a shutdown hook with Runtime.getRuntime().addShutdownHook. Shutdown hooks run on System.exit and on SIGTERM, which is what a container platform sends first, but not on SIGKILL or a JVM crash. So for lines that must not be lost, we also call flush() after writing them, for example after each batch or each important event, and accept a little extra cost in exchange for losing at most the current batch.
4What Else a Reviewer Should Check
First, the closing order of a stream chain. Closing the outermost wrapper is enough and is the correct thing to do, because BufferedWriter.close() flushes its buffer and then closes the writer it wraps, which closes the file. The common mistake is closing the inner FileWriter or FileOutputStream first, by hand or by declaring it as a separate resource that try-with-resources closes before the outer one is flushed: the outer buffer then has nowhere to go and its data is lost, or flushing fails with Stream closed. In try-with-resources, resources close in reverse order of declaration, so declaring only the outer writer, or declaring the inner one first, is safe.
Second, exceptions during writes. If a write fails because the disk is full, the shipper should notice and report it rather than keep writing into a broken stream. PrintWriter is a trap here, because it swallows I/O exceptions and only reports them through checkError().
Third, the meaning of flush. flush() hands data to the operating system, which keeps it in its page cache and writes it to disk later. That survives the JVM exiting, but not a power failure or a kernel crash. If the shipper must guarantee that lines are on disk before it acknowledges them upstream, it needs FileChannel.force(true), the Java equivalent of fsync, or to open the file with StandardOpenOption.DSYNC or SYNC. These are expensive, often milliseconds per call on ordinary disks, so we force per batch rather than per line.
5Follow-up questions
Why does Java not flush open writers automatically at exit?
Because the JVM cannot know which objects are writers, what order they must be closed in, or whether flushing a half-written record is even desirable. Closing is a decision for the application. The only things the JVM runs at exit are registered shutdown hooks, so the application uses them, or framework lifecycle callbacks, to close what it opened.
Would making the buffer smaller fix the problem?
It would reduce how much is lost, not stop it. Any buffer can hold unwritten data at the moment of exit, and a tiny buffer gives up the performance benefit of buffering. The right fix is closing correctly and flushing at the points where losing data is not acceptable.
6Conclusion
In this answer, we saw that a BufferedWriter only writes its buffer when it fills, on flush() or on close(), so a writer that is never closed loses its last partial buffer at exit. The fix is try-with-resources or a close in the shutdown path, with flush() after important writes. A reviewer should also check that the outermost wrapper is the one closed, that write failures are not swallowed, and that durability needs FileChannel.force, because flush only reaches the operating system.
Open with
BufferedWriter collects writes in an in-memory buffer, 8,192 chars by default, and only passes them on when the buffer fills, when I call flush, or when I call close.
Then, if they want more
The shipper never closes the writer, and the JVM does not flush open writers at exit, so whatever is in the last partial buffer is dropped. That is why each file stops at a block boundary and the last lines are missing.
The fix is to close it: try-with-resources when the writer has a clear scope, or, for a long-lived writer, a close in the shutdown path, like a @PreDestroy method in Spring or a shutdown hook, which run on a normal exit and on SIGTERM but not on SIGKILL. For lines that really matter I would also flush after each batch.
As a reviewer I would check a few more things. Close the outermost writer, because its close flushes and then closes the inner stream; closing the inner FileWriter first loses the outer buffer or gives Stream closed. Make sure write errors are not swallowed, for example by PrintWriter, which only reports them through checkError.
And be clear that flush only moves data into the operating system's page cache. If we need the lines on disk before acknowledging them, for example after a power loss, we need FileChannel.force, which is expensive, so I would do it per batch.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A log shipper writes lines through a BufferedWriter and the last lines of each file are...": https://scrivio-interview-library.netlify.app/java/io-and-nio/5375a8dd33/