Search code examples
javaniofile-lockingfilelock

Java NIO FileLock allows other process to write to a locked file


I'm acquiring a lock on a file in one Java application with the following code:

...

File file = new File("/some/file/at/some/path.txt");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

FileLock lock = channel.tryLock();

if (lock != null) {
    Thread.sleep(60000); // Hold lock for 60 seconds 
    lock.release();
}

...

If, during the above 60 seconds, I run another java application with the following code, it isn't able to acquire a lock (as expected) but it still can write.

...

File file = new File("/some/file/at/some/path.txt");
System.out.println(file.canWrite());  // returns true (not expected)

FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
FileLock lock = channel.tryLock();  
System.out.println(lock.toString());  // throws NullPointerException (expected)

...

The same file (while the lock is being held by the first application) is writable by non-Java applications (such as vi, bash, etc.) too. Oracle docs says the lock maps to native locking of underlying OS and hence visible to all programs. Hence, I was expecting the lock to prevent any other process from writing on it.

Am I'm missing something in my code or in my understanding?

I'm running the above code on MacOS Mojave (10.14).


Solution

  • It also says in the docs you link to "Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified."

    So it depends on whether the OS is capable of doing a write lock.