1

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).

Dilip Raj Baral
  • 3,060
  • 6
  • 34
  • 62

1 Answers1

3

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.

mwarren
  • 759
  • 3
  • 6
  • Right. Are there any official/unofficial documentation of behavior of FileLock on various OSes? – Dilip Raj Baral Jun 05 '19 at 10:12
  • Not that I know of. You would need to check for the specific version of OS and the version of JVM you are running on. – mwarren Jun 05 '19 at 10:18
  • Is it at least guaranteed that an application running on one JVM can see the lock acquired by an application in another JVM if it checks for? Like an example in my question. Or this is OS specific too? – Dilip Raj Baral Jun 05 '19 at 14:29
  • 1
    I don't believe that is specified and would again depend on the locking method for the OS. The documentation states that these locks should be considered advisory. – mwarren Jun 05 '19 at 14:40
  • My guess is that file locks are advisory everywhere except on Windows, but don't quote me on that. – TubesHerder Jun 07 '19 at 23:19