OverlappingFileLockException when trying to lock a filechannel twice in shared mode

Siddharth Jain siddhsql at gmail.com
Thu Sep 14 21:21:42 UTC 2023


https://docs.oracle.com/javase%2F7%2Fdocs%2Fapi%2F%2F/java/nio/channels/FileLock.html
A file lock is either *exclusive* or *shared*. A shared lock prevents other
concurrently-running programs from acquiring an overlapping exclusive
lock, *but
does allow them to acquire overlapping shared locks.*

i am running this code on macos aarch64

On Thu, Sep 14, 2023 at 2:18 PM Siddharth Jain <siddhsql at gmail.com> wrote:

> 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/2116c219/attachment-0001.htm>


More information about the nio-dev mailing list