Class FileLock

  • All Implemented Interfaces:
    AutoCloseable

    public final class FileLock
    extends Object
    implements AutoCloseable
    Utility class for obtaining an exclusive lock on a file.

    The FileLock class simplifies the process of locking files, allowing controlled access to shared resources in a multi-threaded environment. It uses Java NIO's FileLock to handle file locks.

    Usage:

    It is recommended to use FileLock with a try-with-resources block to ensure that any underlying file resources are properly released:

    
     Path lockFile = Path.of("example.lock");
     try (FileLock lock = FileLock.of(lockFile)) {
         if (lock.tryLock(1, TimeUnit.MINUTES)) {
             // Perform actions while the file is locked
         } else {
             // Handle inability to acquire lock
         }
     }
     

    Note: An instance of this class should not be shared across different threads.

    Since:
    4.0.0
    Author:
    Dmytro Nosan
    • Method Detail

      • tryLock

        public boolean tryLock​(long timeout,
                               TimeUnit timeUnit)
                        throws FileLockInterruptionException,
                               IOException
        Attempts to acquire an exclusive lock on the file.

        This method tries to acquire a lock on the file within the given timeout period. If the lock is successfully acquired during this time, the method returns true. Otherwise, it returns false after the timeout period has elapsed.

        Parameters:
        timeout - the maximum amount of time to wait for the lock
        timeUnit - the unit of time for the timeout parameter
        Returns:
        true if the lock was successfully acquired, otherwise false
        Throws:
        IllegalArgumentException - if the timeout is negative
        FileLockInterruptionException - if the thread is interrupted while waiting for the lock
        IOException - if an I/O error occurs while trying to acquire the lock
        NullPointerException - if timeUnit is null