Video in progress

Strong Middle 📁 IO and NIO

Two processes want to write to the same file. How does FileLock solve this, and what are its limitations?

FileChannel.lock() takes an OS-level lock; another process can't get it and waits (tryLock returns null immediately). But the lock is usually advisory: a program that doesn't check the lock can still write to the file. And it does not work between threads inside one JVM.

📖 Answer

try (FileChannel ch = FileChannel.open(Path.of("/var/lib/app/state.lock"),
        StandardOpenOption.CREATE, StandardOpenOption.WRITE);
     FileLock lock = ch.tryLock()) {
    if (lock == null) {
        log.info("Boshqa nusxa ishlayapti, chiqamiz");
        return;
    }
    runExclusiveJob();
}

This pattern is used a lot: to make sure two copies of a cron job don't run at the same time on one server.

Limitations to know:

  • the lock belongs to the process. If you try to take it a second time inside one JVM, you get OverlappingFileLockException; for threads use ReentrantLock;
  • on Linux locks are advisory: echo > state.lock works just fine;
  • if the process crashes, the OS releases the lock itself, which is the good side: no "stuck" lock file problem;
  • on NFS the behavior is unreliable and depends on configuration;
  • on some platforms, closing another channel on the locked file also drops the lock.

With several servers, a file lock doesn't help; in that case you need a DB lock (for example ShedLock or SELECT ... FOR UPDATE) or a distributed lock.