Search code examples
javaconcurrencyfilesystemsntfsatomic

How to safely update a file that has many readers and one writer?


I have a set of files. The set of files is read-only off a NTFS share, thus can have many readers. Each file is updated occasionally by one writer that has write access.

How do I ensure that:

  1. If the write fails, that the previous file is still readable
  2. Readers cannot hold up the single writer

I am using Java and my current solution is for the writer to write to a temporary file, then swap it out with the existing file using File.renameTo(). The problem is on NTFS, renameTo fails if target file already exists, so you have to delete it yourself. But if the writer deletes the target file and then fails (computer crash), I don't have a readable file.

nio's FileLock only work with the same JVM, so it useless to me.

How do I safely update a file with many readers using Java?


Solution

  • According to the JavaDoc:

    This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written.