Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one atomically replace a directory with another one in Java?

I have a directory that contains data files served to clients, say, /srv/data. While making a series of updates, I am working on /srv/data_tmp, and at the end of the operation, I would like to atomically replace data with data_tmp. File.renameTo() always returns false for me when the destination is an existing directory. How can I do this?

like image 449
Jean-Philippe Pellet Avatar asked Dec 08 '10 16:12

Jean-Philippe Pellet


2 Answers

I am afraid you can't. Not at the SO level at least. So even if you manage "atomicity" in the context of your java application, you have no guarantee about some other "rogue" process interfering at the actual filesystem level.

If I were you, I'd read this article (quite old, but should give you some ideas) and then see if you can port the suggested approach to a more modern version .

Oh, wait, someone did this already!

And apparently your aren't the first one to ask here, either

Best of luck...

like image 151
p.marino Avatar answered Sep 23 '22 16:09

p.marino


You could replace the /srv/data directory with a symbolic link (or a junction in Windows XP), and change the link's target when appropriate. You won't be able to do that with a Java 6 API though - You'd have to rely on a library or write the command line commands yourself.

NB: I don't guarantee anything about the atomicity of that operation.

like image 33
Jean Hominal Avatar answered Sep 23 '22 16:09

Jean Hominal