Search code examples
javaatomic

Atomic Operation in Java to create a hardlink and delete a file


I am writing a code in JDK 7 on Unix which compares two files. If both files are same say File A and File B.

Then it should delete File B and create a hardlink to File A.

Simple way is :

  1. Compare if files are same
    a. delete File B
    b.  use Path to File B to createLink to File A

But the problem is this is not atomic. So for some reason if my Java code dies after step 1 . I have lost the file.

One Solution is to create backup file and clean it later if process executes fine.

But I am looking for more elegant solution , something in which I can do this as a atomic operation . Please help .

Thanks


Solution

  • The safest approach that I can think of is to create the hard link with a temporary name in the destination directory and then, as the final step, rename it, thus overwriting the destination.

    Your basic algorithm would be something along the lines of the following snippet:

    if (FileContentComparator.same(FileA, FileB)) {
        Files.createLink(TempB, FileA);
        TempB.renameTo(FileB);
    }
    

    Renaming files within the same filesystem is usually atomic and, thus, reasonably safe. The use of a known pattern for the temporary names would allow them to be found and handled, even if the application terminates unexpectedly before performing the final rename.

    At least File.renameTo() will happily overwrite the destination without any hassle - you will have to investigate the behaviour of the Java NIO classes.