OverlappingFileLockException when trying to lock a filechannel twice in shared mode
Siddharth Jain
siddhsql at gmail.com
Thu Sep 14 21:18:25 UTC 2023
Hello,
Using JDK-20, I have this code:
@Test
public void testRR() throws Exception {
var x1 = openForReading(file);
try {
var x2 = openForReading(file);
close(x2);
} finally {
close(x1);
}
}
private RafChannelPair openForReading(String filename) throws
FileNotFoundException, IOException {
RandomAccessFile raf = new RandomAccessFile(filename, "r");
FileChannel channel = raf.getChannel();
var lock = channel.tryLock(0, Long.MAX_VALUE, true);
if (lock != null && !lock.isShared()) {
System.out.println("Unable to acquire shared lock");
}
return new RafChannelPair(raf, channel, lock);
}
private void close(RafChannelPair x) throws IOException {
if (x.lock != null) {
x.lock.release();
}
x.channel.close();
x.raf.close();
}
I expect the code to throw no exception but when I run it I get:
[ERROR] testRR(com.mycompany.app.FileLockingTest) Time elapsed: 0.007 s
<<< ERROR!
java.nio.channels.OverlappingFileLockException
at com.mycompany.app.FileLockingTest.openForReading(FileLockingTest.java:69)
at com.mycompany.app.FileLockingTest.testRR(FileLockingTest.java:52)
is this not a bug? can someone explain it to me? if this is as expected
then what difference does it make whether one gives true or false to the
shared parameter of public abstract FileLock
<https://docs.oracle.com/javase%2F7%2Fdocs%2Fapi%2F%2F/java/nio/channels/FileLock.html>
tryLock(long position,
long size,
boolean shared)
Thanks,
M.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/nio-dev/attachments/20230914/4dd6af13/attachment.htm>
More information about the nio-dev
mailing list