How can I aquire two shared FileLocks? I have the following test code:
File file = new File(lockDir, "tmp.lock");
file.createNewFile();
FileChannel channel = new RandomAccessFile(file, "r").getChannel();
boolean shared = true;
FileLock lock1 = channel.tryLock(0, Long.MAX_VALUE, shared);
assertTrue(lock1.isValid());
assertTrue(lock1.isShared());
// I get an OverlappingFileLockException here:
FileLock lock2 = channel.tryLock(0, Long.MAX_VALUE, shared);
assertTrue(lock2.isValid());
assertTrue(lock2.isShared());
lock1.release();
lock2.release();
But I get an OverlappingFileLockException in the marked line, even if I execute the lock-aquiring in two different threads. Or is a shared lock only possible for two different processes? Or did I misunderstood sharing and it is only about having write&read access for portions of a file ('sharing the file resource')? I cannot really find docs about whether my use case is possible or not.
I would like to have the same behaviour for the file based locking that one gets for new ReentrantReadWriteLock()
with .readLock()
and .writeLock()
where multiple read-locks are allowed but only one write lock.