0

I need to be able to have multiple processes accessing a single file such that there is at most one writer but potentially multiple readers that have the file open at the same time (enforced at file opening time). If the writer decides to update a certain byte range, the readers must not access that byte range until the writer is finished with its update.

I can express the file level sharing in C# using FileAccess.ReadWrite/FileShare.Read when opening the file for writing and FileAccess.Read/FileShare.ReadWrite when opening the file for reading. This also disallows any further writers.

Byte ranges can then be temporarily locked for reading/updating using FileStream.Lock (or, as unfortunately shared locks are not available in the basic C# APIs, calling Window's system API function LockFileEx).

Is there a way to express this behavior in Java (targeting linux) without resorting to introducing a separate lock file to manage file level sharing? I.e. how can I specify sharing when opening a file in Java and then perform separate locking on byte ranges?

I did check various API documentation for RandomAccessFile and FileChannel. While I did find something about byte range locking, there does not appear to be anything about file sharing and access limitations for other processes accessing the same file.

Michael
  • 1
  • 1
  • 2
  • 1
    FileLock is delegated to the underlying operating system. I guess it prevents for other processes make a "file lock violation" situation. Bad news, Java cannot guarantee that FileLock works perfectly on a certain operating- and file system. Take a look at [Platform Dependencies](https://docs.oracle.com/javase/8/docs/api/java/nio/channels/FileLock.html) section. And here is a [groundwork](https://stackoverflow.com/a/58871479/5043481) to test it. – zforgo Apr 21 '23 at 22:18
  • ["mapped byte buffer"(random access file, nio channel)](https://stackoverflow.com/search?tab=votes&q=Mappedbytebuffer&searchOn=3) sounds promising... – xerx593 Apr 21 '23 at 22:26
  • I can’t tell from your wording whether a [shared lock](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/nio/channels/FileChannel.html#tryLock(long,long,boolean)) an acceptable solution or not. – VGR Apr 21 '23 at 22:53
  • I do know about FileLock, accessible via FileChannel. However, my needs go beyond that. I was hoping that I don't have to add some custom "advisory" sharing on top of the "advisory" locks provided by FileLock on linux, but rather get something that already exists. – Michael Apr 22 '23 at 12:58
  • How does MappedByteBuffer help me with sharing/locking? I didn't see anything relevant in the API documentation. – Michael Apr 22 '23 at 12:59

0 Answers0