File Locking (and the JVM)

languages
systems
I originally posted this on 2010/07/23 on my personal blog. File locks control access to a file…
Published

January 12, 2024

I originally posted this on 2010/07/23 on my personal blog.


File locks control access to a file or a range of bytes within a file. This is necessary in situations where multiple simultaneously executing programs need to modify the same file.

File locking functionalities are provided within the NIO API, or more specifically in the java.nio.channels package.

The two most important classes for file locking are java.nio.channels.FileChannel and java.nio.channels.FileLock.

Several methods provide file locking:

FileLock FileChannel.lock()
FileLock FileChannel.lock(long position, long size, boolean shared)
FileLock FileChannel.tryLock()
FileLock FileChannel.tryLock(long position, long size, boolean shared)

lock() acquires an exclusive lock on the entire file, and blocks until the lock is acquired, tryLock() is identical but returns null if the lock cannot be acquired. The methods with parameters lock only regions of a file, the shared parameter is true for a shared lock and false for an exclusive lock.

A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks. An exclusive lock prevents other programs from acquiring an overlapping lock of either type.

Once you don’t need the lock anymore, release it with FileLock.release().

That seems to be a great solution, but there are limitations, related to the operating system the JVM runs on: