I have a cluster of machines, each running a Java app.
These Java apps need to access a unique resource.txt file concurently.
I need to atomically rename a temp.txt file to resource.txt in Java, even if resource.txt already exist.
Deleting resource.txt and renaming temp.txt doesn't work, as it's not atomic (it creates a small timeframe where resource.txt doesn't exist).
And it should be cross-platform...
Thanks !
解决方案
For Java 1.7+, use java.nio.file.Files.move(Path source, Path target, CopyOption... options) with CopyOptions "REPLACE_EXISTING" and "ATOMIC_MOVE".
For example:
Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);