Separate atomic file visibility, provider-specific replacement, competing writers and crash durability in a Java implementation.
Atomic visibility is a narrower promise than durable replacement
Writing a configuration file in place can expose a partial document to another process. A common alternative writes a complete temporary file and then moves it into place. Java offers StandardCopyOption.ATOMIC_MOVE for an atomic filesystem move, but the option does not promise every property applications often attach to the word atomic. Existing-target replacement is implementation specific, and crash durability needs separate reasoning.
This evergreen guide uses a synthetic configuration containing a generation number and a checksum. One writer prepares new generations while readers reopen the target. No real application configuration is modified. The teaching objective is to separate three questions: can a reader see a partial file, can a concurrent writer overwrite another generation, and will the new directory entry survive a power failure?
The Java Files.move documentation is unusually important here. With ATOMIC_MOVE, other move options are ignored. If the target exists, the provider can replace it or fail. If atomic movement is unsupported, AtomicMoveNotSupportedException is the expected signal. Adding REPLACE_EXISTING does not turn the operation into a portable atomic replacement contract across all providers.
Prepare the new bytes beside the destination
Create the temporary file in the destination directory. This improves the chance that source and target are on the same filesystem and provider, which is a necessary practical condition for many atomic rename implementations. It is not proof that ATOMIC_MOVE will succeed. A default temporary directory on another volume introduces an avoidable cross-filesystem failure.
Validate the complete configuration before publishing its path. Parsing or checksum verification after the move would allow an invalid generation to become visible. Put size bounds on the input, choose an explicit encoding and define which file attributes the replacement should have. A new temporary file does not automatically inherit every permission or ownership property of the old destination.
// Author: Sandeep Belgavi. Original example for a disposable directory.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.*;
import static java.nio.file.StandardCopyOption.ATOMIC_MOVE;
import static java.nio.file.StandardOpenOption.WRITE;
final class AtomicConfig {
static void publish(Path target, byte[] complete) throws IOException {
Path absolute = target.toAbsolutePath();
Path temporary = Files.createTempFile(absolute.getParent(),
".config-", ".tmp");
try {
try (FileChannel channel = FileChannel.open(temporary, WRITE)) {
ByteBuffer buffer = ByteBuffer.wrap(complete);
while (buffer.hasRemaining()) channel.write(buffer);
channel.force(true);
}
Files.move(temporary, absolute, ATOMIC_MOVE);
} finally {
Files.deleteIfExists(temporary);
}
}
}This core assumes the bytes were already validated, that the parent directory is trusted and that the caller accepts provider-specific behavior for an existing target. It fails if the provider cannot perform the move; it does not silently weaken the contract. Production code should also preserve the original failure if cleanup fails, instead of allowing a cleanup exception to obscure it.
Understand what readers can observe
For a supported atomic move, a reader resolving the destination sees the old directory entry or the new one rather than an intermediate copied prefix. A reader that already opened the old file may continue reading the old object. Atomic path replacement is not a mechanism for updating every existing file handle in every process.
A reader should open the file once and parse that opened generation. Reading the generation field in one open and the payload in a second can combine two valid versions if a replacement happens between opens. The same issue appears when a configuration spans several files. Individually atomic file moves do not make the group atomic.
For a multi-file configuration, consider writing an immutable versioned directory and atomically changing a small manifest or pointer where the platform supports the required operation. Readers resolve the selected generation once and keep using it for the duration of the operation. The design still needs cleanup of old generations and a compatibility policy for readers that remain active.
Failure before and after the move
If writing or validation fails before the move, the old target should remain intact and the temporary file should be cleaned up when possible. A process crash can leave an orphan temporary file, so give temporary files a recognizable naming convention and a cautious retention-based cleanup procedure. Never delete arbitrary files merely because their names resemble the prefix.
If ATOMIC_MOVE is unsupported, propagate the failure or use an explicitly different protocol. Falling back to copy-and-delete changes the visibility guarantee. If such a fallback is acceptable for a particular application, surface it as a separate mode with separate tests and documentation. A catch block that quietly performs a non-atomic move is a contract change hidden in error handling.
After a successful move, the temporary path normally no longer exists. The final cleanup is harmless in that case. If the provider reports a failure, inspect the documented provider behavior and the actual target state before blindly retrying. Avoid assuming that every I/O exception identifies the same point in the operation.
Force the data without overstating durability
FileChannel.force requests that updates associated with the channel be forced to storage according to its documented guarantees. Calling it before moving the file addresses the new file's contents. It does not by itself establish a portable guarantee that the later directory-entry change is durable after power loss.
Filesystems, operating systems, network filesystems and storage devices differ. Some durable-replacement protocols require synchronizing the parent directory after rename. Java's general Files.move API does not provide a universal cross-platform transaction over file data and directory metadata. If crash durability is a hard requirement, choose and document a supported platform-specific protocol or a storage system that provides the required transaction semantics.
Do not claim a crash test because a normal process exit succeeded. Killing a process, restarting an operating system and cutting storage power exercise different failure models. An ordinary unit test can verify visible content and error handling; it cannot prove every storage persistence guarantee. Report the tested operating system, filesystem provider and Java version with the result.
Atomic movement does not prevent lost updates
Two writers can each prepare a complete configuration and move it into place successfully. Readers see complete files, but the later writer may overwrite the earlier writer's changes. That is a concurrency-control problem, not a partial-write problem. Add a single-writer service, an appropriate lock or a compare-and-swap protocol backed by a storage system that supports it.
A generation number inside the document helps detect unexpected changes, but checking it before rename is not an atomic compare-and-swap. Another writer can publish between the check and the move. A lock must cover the read-modify-publish sequence and be honored by every writer. If that cannot be guaranteed, a file may be the wrong coordination primitive.
Keep the destination path under application control. Symbolic links, directory replacement and attacker-controlled parent paths introduce security concerns that the ATOMIC_MOVE option does not solve. This guide's disposable trusted directory is an explicit constraint, not a claim that the sample is a secure arbitrary-path file-writing service.
Verify the boundary you promise
Run a reader loop that repeatedly opens and validates complete synthetic generations while the writer publishes replacements. Every observed document should satisfy the checksum and parse contract. Accept old or new generations; do not require an already open reader to switch immediately. Record a provider refusal separately from a content-validation failure.
Test validation failure before publishing, a missing parent directory, an existing target and cleanup after a failed write. Add an injected unsupported-atomic-move path to verify that the application reports the failure without a silent weaker fallback. Keep the real provider integration test distinct from injected unit tests.
The local Windows fixture with JDK 23.0.2 created the first file and replaced the existing target before the concurrent-reader phase. During that phase, a later atomic move returned AccessDeniedException. The retained log establishes the refusal, not its underlying operating-system cause. The companion now reports completed replacements and refusal separately from its content-integrity assertions. It performs no retry or weaker move. This observation is a useful limit on the tested environment, not a portable conclusion that every Windows reader prevents replacement.
The useful promise is precise: on a supported provider, one validated file generation becomes visible through an atomic move, under the stated writer and path assumptions. Durability, multi-file consistency and competing-writer control remain separate contracts. Making those boundaries explicit is what turns a familiar temporary-file recipe into an implementation readers can assess and safely adapt.
Run the example yourself
The synthetic fixtures, expected output and tests behind this guide are in the companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.