Class FileLocker


  • public class FileLocker
    extends Object

    Simple FileLock wrapper to use operating-system file-locking ability to help with multi-processes management. No instance of the file being locked is returned by this class. It's main purpose is to prevent other processes from trying to acquire a lock when it is not desirable to do so. For instance, it can be used as a way to guarantee only one instance of a specific process can run per operating system and file system.

    The lock(), tryLock(), and unlock() are similar to FileChannel.lock(), FileChannel.tryLock(), and FileLock.release() but with slightly different behaviors. Refer to the corresponding method documentation for more detail.

    Since:
    2.0.0
    Author:
    Pascal Essiembre
    • Constructor Detail

      • FileLocker

        public FileLocker​(Path lockFile)
    • Method Detail

      • tryLock

        public boolean tryLock()
                        throws IOException

        Tries to locks the unlocked file and returns true when successful. If the file does not exist, an empty file is created. If the file exists and is already locked, this method silently fails and returns false.

        Returns:
        true if file was successfully locked.
        Throws:
        IOException - could not lock
        See Also:
        lock()
      • lock

        public void lock​(boolean block)
                  throws IOException

        Locks the unlocked file. If the file does not exist, an empty file is created. If the file exists and is already locked, this method throws a FileAlreadyLockedException.

        Parameters:
        block - set to true to wait for an available lock
        Throws:
        IOException - could not lock
      • unlock

        public void unlock()
                    throws IOException

        Unlocks the locked file. Unlocking an inexistent or already unlocked file has no effect.

        Throws:
        IOException - could not unlock
      • isLocked

        public boolean isLocked()
        Gets whether the file is locked.
        Returns:
        true if locked.