Class FileLock


  • @Internal
    public class FileLock
    extends Object
    A file lock used for avoiding race condition among multiple threads/processes.
    • Constructor Detail

      • FileLock

        public FileLock​(String fullPath)
        Initialize a FileLock using a file located at fullPath.
        Parameters:
        fullPath - The path of the locking file
      • FileLock

        public FileLock​(String parentDir,
                        String fileName)
        Initialize a FileLock using a file located at parentDir/fileName.
        Parameters:
        parentDir - The parent dir of the locking file
        fileName - The name of the locking file
    • Method Detail

      • inTempFolder

        public static FileLock inTempFolder​(String fileName)
        Initialize a FileLock using a file located inside temp folder.
        Parameters:
        fileName - The name of the locking file
        Returns:
        The initialized FileLock
      • tryLock

        public boolean tryLock()
                        throws IOException
        Try to acquire a lock on the locking file. This method immediately returns whenever the lock is acquired or not.
        Returns:
        True if successfully acquired the lock
        Throws:
        IOException - If the file path is invalid
      • unlock

        public void unlock()
                    throws IOException
        Release the file lock.
        Throws:
        IOException - If the FileChannel is closed
      • unlockAndDestroy

        public void unlockAndDestroy()
                              throws IOException
        Release the file lock, close the fileChannel and FileOutputStream then try deleting the locking file if other file lock does not need it, which means the lock will not be used anymore.
        Throws:
        IOException - If an I/O error occurs
      • isValid

        public boolean isValid()
        Check whether a FileLock is actually holding the lock.
        Returns:
        True if it is actually holding the lock