Java › I/O & NIO
How would you implement file locking (using FileLock) to coordinate exclusive access to a shared file across multiple processes, and what are the platform-specific reliability caveats?
AdvancedAnswer
FileChannel.lock() (blocking) or tryLock() (non-blocking, returns null if unavailable rather than waiting) acquires an advisory OS-level file lock on all or part of a file, coordinating access between multiple processes (not just threads within the same JVM) attempting to read/write the same file concurrently -- an important caveat is that file locks in Java are advisory on most platforms (meaning they only prevent conflicts between processes that explicitly check for and respect the lock, not an OS-enforced hard restriction preventing any access whatsoever), and locking behavior/reliability can vary meaningfully across operating systems and especially over network file systems (NFS), making file-based locking a reasonably reliable coordination mechanism for local, single-machine scenarios but a poor choice for distributed coordination across multiple machines, where a dedicated distributed lock service is more appropriate.
try (FileChannel channel = FileChannel.open(Path.of("shared.lock"), StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
FileLock lock = channel.tryLock();
if (lock == null) {
System.out.println("Another process already holds the lock");
return;
}
try {
// perform exclusive work protected by the lock
} finally {
lock.release();
}
}Real-world example A scheduled batch job that should only ever run as a single instance across a cluster of application servers sharing a network file system uses FileLock as a simple coordination mechanism to prevent duplicate concurrent runs, while acknowledging the team's awareness that this approach carries known reliability caveats specifically over network file systems compared to local disk.