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:
- Some systems only provide advisory file locking: applications that don’t acquire locks may still write the file.
- Some systems make it impossible to lock a file and map it into memory. On those, you won’t be able to use a
MappedByteBuffer
to access file. - File locks are held by the Java Virtual Machine, not by individual programs. Two programs in the same JVM won’t be able to simultaneously acquire a lock on the same file.
- Opening multiple channels on the same locked file should be avoided, as on some systems, closing a channel on a file releases all locks on the file held by the same JVM.
- On networked file systems, file locking should be avoided – or at least, relying on file locking mechanisms should be avoided, as it’s dependent on the networked file system implementation.
Top comments (0)