Raedwald Raedwald - 7 months ago 12
Java Question

Is a Java FileLock a POSIX advisory (fcntl) lock

I have a C++ program that locks files using POSIX advisory locks. That is, it uses the POSIX

system call for lock operations. I want a Java program to interoperate with that C++ program, so I want my Java program to also use POSIX advisory locks. File locking in Java should use the standard
FileLock
class. But the API documentation is understandably vague on just how locking is implemented:


This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written.


If I am running a common implementation of Java (Oracles, Open JDK) on a POSIX operating system, or more specifically a GNU/Linux system, is it safe to assume that the Java
FileLock
class uses POSIX advisory locks?

Answer

Some Unix operating systems, including Linux, provide BSD-style (flock) locks, so it might be thought that Java FileLock could be implemented using BSD-style locks rather than POSIX locks. But that is not possible, because BSD-style locks are whole-file locks rather than record locks, and FileLock is a record lock: each lock is for a range of bytes in a file. Thus there is no real choice on a Unix system, and assuming that the implementation of FileLock uses POSIX fcntl locks is a safe assumption on a Unix operating system.

The resulting FileLock locks might or might not interact with BSD-style locks. BSD-style locks can be implemented using POSIX locks (this was the case for Linux before version 2.0), or the operating system might have the two styles of locking interact (this is the case for FreeBSD). But in general that can not be guaranteed, and BSD-style locks and Java locks might be effectively invisible to each other (this is the case for any version of Linux you are likely to encounter).

Comments