Search code examples
javafileatomicdirectory

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?


Solution

  • 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...