Is a move operation in Unix atomic?
A UNIX rename
operation is atomic (see rename(2)). The UNIX mv
command uses rename if the source and target path are on the same physical device. If the target path is on a different device, the rename will fail, and mv
will copy the file (which is not atomic).
If the target file path exists, the rename
will atomically remove it from the file system and replace it with the new file. The file won't actually be deleted until its reference count drops to zero, so if another process is currently reading the file, it will keep reading the old file. Once all processes have closed the old file, its reference count will drop to zero and the file storage space will be reclaimed.
why not use FileChannel.lock
?
here is an example:
http://examples.javacodegeeks.com/core-java/nio/filelock/create-shared-file-lock-on-file/
- move(rename) is atomic if done on the same device. (device = same disk/partition)
- If
Foo.txt
exits moveFoo.tmp
toFoo.txt
most likely will fail. (But if you first deleteFoo.txt
and then move, it should work). What happens is that a file is not physically deleted until all file handlers are closed (there is no process that uses that file). Also, after remainingFoo.tmp
toFoo.txt
you will have 2 Foo.txt files. One that is deleted but still opened in memory (basically that file does not have a reference on disk anymore) and one that actually resides on disk. - But, after move, in second process you need to reopen the file.
Let me know if we are on the same page with #1.