Quick revision
The short answer
Readers see half-written files because the service overwrites the state file in place, so for a moment the file holds only part of the new JSON. Instead we write the new content to a temporary file in the same directory and then rename it over the old one with Files.move and ATOMIC_MOVE. A rename within one file system is atomic on common operating systems, so readers see either the complete old file or the complete new one; we call FileChannel.force(true) before the move if the file must survive a crash, readers open the file by name each time, and on Windows we handle a replace that fails because a reader has the file open.
What to remember
In this answer, we saw that writing a file in place leaves moments where it is empty or partial, which is what readers observed. Writing to a temporary file in the same directory and then using Files.move with ATOMIC_MOVE publishes the new content in one step, because a rename within one file system is atomic on common operating systems. We add FileChannel.force(true) before the move for crash safety, make readers open the file by name each time, and handle failed replaces on Windows with retries.
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.
Readers see half-written files because the service overwrites the state file in place, so for a moment the file holds only part of the new JSON. Instead we write the new content to a temporary file in the same directory and then rename it over the old one with Files.move and ATOMIC_MOVE. A rename within one file system is atomic on common operating systems, so readers see either the complete old file or the complete new one; we call FileChannel.force(true) before the move if the file must survive a crash, readers open the file by name each time, and on Windows we handle a replace that fails because a reader has the file open.
Why this question is asked
Sharing state between processes through a file is common: a service writes its configuration, a leader election result or a progress marker, and sidecars, scripts or other services read it. It works until a reader parses the file at the exact moment it is being rewritten and gets truncated JSON, which can crash the reader or, worse, make it act on a partial value. Interviewers ask this scenario because the correct pattern is short, but each step has a reason, and the edge cases separate a careful engineer from someone who has only seen the happy path. In this answer, we will see why in-place writes are not atomic, build the write-then-rename pattern, add durability, and cover the reader side and Windows.
1Why Writing In Place Is Not Atomic
Writing a file in place, for example with Files.writeString(path, json) or a FileWriter, happens in steps. Opening the file with the usual options truncates it to zero bytes. The content is then written in one or more write calls, and with a buffered writer, in blocks of a few kilobytes. Between those steps the file exists with no content or with only part of the new content. A reader that opens the file during that window reads what is there and gets an empty string or a JSON document cut off in the middle.
The window is small, often well under a millisecond, which is why the problem appears only occasionally. But with readers polling every second and the writer updating frequently, occasionally means several times a day.
2Write to a Temporary File, Then Rename
A rename is different from a write. On Linux, macOS and other POSIX systems, rename() of a file to a name that already exists replaces the directory entry in one step: at any instant the name points either to the old file or to the new one. So we put all the slow, multi-step writing into a file that no reader knows about, and use the rename to publish it in a single step.
5 messages in order. Play them, or step through them one at a time.
Readers only ever open state.json, which always names a complete file.
Notice that the temporary file is created in the same directory as the target. The reason is that a rename is only atomic within one file system. If the temporary file were in /tmp and the target on another mount, the move would have to copy the data, which is again a multi-step write. With ATOMIC_MOVE, Files.move refuses to do that and throws AtomicMoveNotSupportedException instead, which is exactly what we want: the code fails loudly rather than silently losing atomicity. The unique temporary name also means two writers never overwrite each other's temporary files.
3Making It Survive a Crash
Atomic visibility and durability are two separate properties. Without force(), the new data may still be only in the operating system's page cache when the rename happens. If the machine loses power at that moment, the file system may come back with the rename applied but the data not yet written, leaving an empty or zero-filled state file, which is the half-written file problem in a new form. Calling FileChannel.force(true) before the move, the Java form of fsync, makes sure the content is on disk before we make it visible. For the rename itself to be durable, the directory entry must also be flushed. Java has no portable API for fsync on a directory; on Linux, opening the directory with FileChannel.open(dir, READ) and calling force(true) works in practice, but it is not guaranteed by the specification, so check your platform if you need it. If losing the very latest update after a power failure is acceptable, as it often is for a state file that will be rewritten soon, force on the file alone is enough.
4The Reader Side
The rename trick protects readers that open the file by name. On POSIX systems, a reader that already has the old file open keeps reading the old file, even after it has been replaced, because its handle points to the old file's data, not to the name. So a reader that opens the file once at startup and re-reads through the same handle will never see updates. Readers must open the file by name each time they want the current state, read it fully and close it.
Readers should also ignore our temporary files, which matters if they scan the directory rather than reading one name, so we give temporary files a clear suffix such as .tmp. And readers should still validate what they parse, because a bug or a manual edit can produce bad JSON; a reader that keeps its last good state when parsing fails is far more robust than one that crashes.
5Windows and Other Edge Cases
Windows behaves differently. A file that another process has open can only be replaced if that process opened it with a sharing mode that allows deletion. Whether it did depends on the reader: some Java APIs open files that way, but many readers, including older java.io classes, non-Java tools and antivirus scanners, do not, so check how your readers open the file. So on Windows the Files.move with ATOMIC_MOVE can fail with an AccessDeniedException or FileSystemException while a reader holds the file. We handle that by retrying a few times with a short delay, keeping readers' open time short, and alerting if retries keep failing.
Network file systems are another edge case. Atomic rename semantics on NFS and SMB shares depend on the server and client configuration, and caching can make readers on other machines see stale content for a while. If several machines share the state, a small database or a key-value store is often a better tool than a shared file. For a single host, the write-then-rename pattern is the standard answer, and it is what many tools, from editors to package managers, use.
6Follow-up questions
Why not use a file lock instead?
File locks in Java, through FileChannel.lock, are advisory on most Unix systems: they only work if every reader also takes the lock, and a script using cat or a tool in another language will ignore them. Locks also block readers while the writer works and are easy to leave held after a crash. The rename approach needs no cooperation from readers at all, which is why it is preferred for publishing files.
What is the full write loop for a FileChannel?
A single channel.write call may write fewer bytes than the buffer holds, so robust code loops: ByteBuffer buf = UTF_8.encode(json); while (buf.hasRemaining()) ch.write(buf). For a small state file the first call almost always writes everything, but the loop costs nothing and removes the doubt. Alternatively, Files.writeString(tmp, json, UTF_8) followed by opening a channel just to call force works too.
7Conclusion
In this answer, we saw that writing a file in place leaves moments where it is empty or partial, which is what readers observed. Writing to a temporary file in the same directory and then using Files.move with ATOMIC_MOVE publishes the new content in one step, because a rename within one file system is atomic on common operating systems. We add FileChannel.force(true) before the move for crash safety, make readers open the file by name each time, and handle failed replaces on Windows with retries.
Open with
The readers see half-written files because we overwrite the file in place: opening it truncates it, and the content arrives in several writes, so for a short moment the file is empty or partial.
Then, if they want more
I would write the new JSON to a temporary file in the same directory, with a unique name and a .tmp suffix, and then call Files.move(tmp, target, ATOMIC_MOVE). A rename within one file system is atomic on Linux, macOS and other common systems, so the name always points to either the complete old file or the complete new one.
The temp file has to be in the same directory, or at least the same file system, because across file systems a move is a copy, and with ATOMIC_MOVE Java will throw instead of silently copying.
If the file must survive a crash or power loss, I write it through a FileChannel and call force(true) before the move, otherwise the rename can hit the disk before the data does.
On the reader side, readers must open the file by name every time, because a handle opened earlier keeps pointing at the old file after the rename, and they should skip .tmp files and keep their last good state if parsing fails.
On Windows, a reader holding the file open can block the replace, so I would retry the move a few times and alert if it keeps failing.
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 service writes a JSON state file that other processes read. Occasionally readers see a...": https://scrivio-interview-library.netlify.app/java/io-and-nio/e5712b3526/