Piotr Podraza
Piotr Podraza

Reputation: 2029

Atomic move and many processes running it at the same time

In my application I have scheduled task that monitor a directory for files with certain extension. Those files are further processed. There can be a multiple processes executing this app and to prevent multiple instances from processing the same file I change its extension so its not listed another time using Files.move with ATOMIC_MOVE option. There is a chance that more than one instance of app try to execute this method at the same time though - my question is: what happens then? Should I expect some exceptions being thrown?

Upvotes: 5

Views: 1410

Answers (1)

Hugues M.
Hugues M.

Reputation: 20467

You should be able to count on a correct behavior: first one "wins", second one gets java.nio.file.NoSuchFileException, so you catch that particular exception and ignore the file.

try {
    Files.move(previousPath, renamedPath, StandardCopyOption.ATOMIC_MOVE);
}
catch (NoSuchFileException e) {
    /* Another process has already processed that file. Ignore and move on. */
}
catch (IOException e) {
    /* Must handle that one: something else has failed */
}

I've verified on Linux and macOS with a program that lists a directory with some files, and renames them all with a random UUID, and running several instances of that program on the same directory for a while. I got many NoSuchFileException but nothing else.

I would be quite confident with this on a local filesystem. However, if you're using that on a networked filesystem (NFS...), all bets are off.

Upvotes: 4

Related Questions