Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomic file write operations (cross platform)

How do I build up an atomic file write operation? The file is to be written by a Java service and read by python scripts.
For the record, reads are far greater than writes. But the write happens in batches and tend to be long. The file size amounts to mega bytes.

Right now my approach is:

  • Write file contents to a temp file in same directory
  • Delete old file
  • Rename temp file to old filename.

Is this the right approach? How can avoid conditions where the old file is deleted but the new filename is yet to be renamed?

Do these programming languages (python and java) offer constructs to lock and avoid this situation?

like image 602
Quintin Par Avatar asked Jan 12 '10 13:01

Quintin Par


People also ask

What is atomic file system operation?

An atomic file operation is an operation that cannot be interrupted or "partially" performed. Either the entire operation is performed or the operation fails.

What is an atomic write?

For example, an atomic read / write operation. Or atomic access to a property. But what does this mean? Generally, you can summarize atomic as "one at a time". For example, when accessing or mutating a property is atomic, it means that only one read or write operation can be performed at a time.


3 Answers

AFAIK no.

And the reason is that for such an atomic operation to be possible, there has to be OS support in the form of a transactional file system. And none of the mainstream operating system offer a transactional file system.

EDIT - I'm wrong for POSIX-compliant systems at least. The POSIX rename syscall performs an atomic replace if a file with the target name already exists ... as pointed out by @janneb. That should be sufficient to do the OP's operation atomically.

However, the fact remains that the Java File.renameTo() method is explicitly not guaranteed to be atomic, so it does not provide a cross-platform solution to the OP's problem.

EDIT 2 - With Java 7 you can use java.nio.file.Files.move(Path source, Path target, CopyOption... options) with copyOptions and ATOMIC_MOVE. If this is not supported (by the OS / file system) you should get an exception.

like image 120
Stephen C Avatar answered Oct 05 '22 13:10

Stephen C


It's a classic producer/consumer problem. You should be able to solve this by using file renaming, which is atomic on POSIX systems.

like image 20
gruszczy Avatar answered Oct 05 '22 11:10

gruszczy


At least on POSIX platforms, leave out step 3 (delete old file). In POSIX, rename within a filesystem is guaranteed to be atomic, and renaming on top of an existing file replaces it atomically.

like image 40
janneb Avatar answered Oct 05 '22 13:10

janneb