How to safely update a file with many readers and one author?

I have a set of files. The set of files is read-only from the NTFS share, so there can be many readers. Each file is periodically updated by one author who has write access.

How to ensure that:

  • If the write failed, the previous file is still readable.
  • Readers Cannot Delay Single Writer

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

nio FileLock only works with one JVM, so it is useless to me.

How to safely update a file with many readers using Java?

+3
source share
6 answers

According to JavaDoc :

API . , , , , , , .

+3

, , Vista/Windows Server 2008, TxF ( NTFS), , API JNI.

, , - , , / .

+1

Unix , . , , , , . , NTFS , , BSD, , , .

+1

-, , , .. .

, "settings1.ini", , "settings2.ini.wait", , "settings2.ini", "settings1.ini".

settings2.ini, settings1.ini last .

, .

+1

. FS API Windows, NTFS , , AFAIK, , :

, , -. , .

.

, . , Windows . , , . , . , . ( , Mac OS X "ExchangeObjects", - , Windows ).

, , , , . , , .

, Java. , API.

, .

0

I was dealing with something similar recently. If you are using Java 5, maybe you might consider locking NIO files in conjunction with ReentrantReadWriteLock? Ensure that all code referencing the FileChannel object also references ReentrantReadWriteLock. Thus, the NIO locks it at the VM level, while the retentate lock blocks it at the level of each thread.

FileLock fileLock = filechannel.lock(position, size, shared);
reentrantReadWriteLock.lock();

// do stuff

fileLock.release();
reentrantReadWriteLock.unlock();

Of course, some exception handling will be required.

-one
source

All Articles