Course contentsShow
← Java
Lesson 2059 of 2,87041. NIO.2 and the Path APIFree lesson

ATOMIC_MOVE: Ensuring Move Atomicity

Use StandardCopyOption.ATOMIC_MOVE to guarantee atomic file moves within the same filesystem.

ATOMIC_MOVE: Ensuring Move Atomicity

What you'll learn: How to use StandardCopyOption.ATOMIC_MOVE to guarantee file moves happen completely or not at all.

The Atomicity Problem

When you move a file using Files.move(), the operation normally happens in steps: copy the data, then delete the source. If something goes wrong mid-operation (power failure, crash, etc.), you could end up with partial data or inconsistent state. ATOMIC_MOVE solves this by making the move operation atomic — it either completes entirely or fails entirely, with no in-between state.

Think of it like a bank transfer: you wouldn't want money to leave one account but never arrive in the other. An atomic move ensures the file is either at the source location or the destination, never half-copied or lost.

How It Works

Path source = Paths.get("data.txt");
Path target = Paths.get("archive/data.txt");

Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);

This tells the filesystem to perform the move as a single, indivisible operation. The file instantly appears at the new location with no intermediate state visible to other processes.

Important Constraints

ATOMIC_MOVE only works within the same filesystem. If source and target are on different drives or partitions, the operation will throw an AtomicMoveNotSupportedException. The filesystem must also support atomic moves (most modern ones do).

This option is especially valuable in production systems where multiple processes might be watching or accessing files, and consistency is critical.

Key Takeaway: Use StandardCopyOption.ATOMIC_MOVE with Files.move() to guarantee all-or-nothing file moves within the same filesystem, eliminating the risk of partial moves or inconsistent states.