0

I haven't worked with nio much and I'm having some trouble with releasing a FileLock. Basically, in JVM-A I have a NON-SHARABLE write lock on a file which looks something like this:

File lockfile = new File("m.lock");
RandomAccessFile writeFile = new RandomAccessFile(lockfile, "rw");
FileChannel writeChannel = writeFile.getChannel();
FileLock writeLock = writeChannel.tryLock(0L, Long.MAX_VALUE, false);

Then in JVM-B I try to create a SHARABLE read lock on the same file which looks something like this:

File lockfile = new File("m.lock");
RandomAccessFile readFile = new RandomAccessFile(lockfile, "r");
FileChannel readChannel = readFile.getChannel();
FileLock readLock = readChannel.tryLock(0L, Long.MAX_VALUE, true);  
while (readLock == null) {
    System.out.println("unable to get lock");
    Thread.sleep(5000);
    readLock = readChannel.tryLock(0L, Long.MAX_VALUE, true);
}

My problem is that JVM-B loops forever and never gets a SHARABLE read lock. Even if JVM-A does writeLock.release(); writeChannel.close(); and writeFile.close(); and even if JVM-A exits and is no longer running, JVM-B is still not able to get a SHARABLE read lock on the file.

So what am I missing here?

Michael Remijan
  • 687
  • 7
  • 22

1 Answers1

0

My mistake everyone, I found my error. My code looked like this:

readChannel.tryLock(0L, Long.MAX_VALUE, true);

instead of this:

readLock = readChannel.tryLock(0L, Long.MAX_VALUE, true);

I missed the variable assignment.

Michael Remijan
  • 687
  • 7
  • 22