Class FileLocker
- java.lang.Object
-
- com.norconex.commons.lang.file.FileLocker
-
public class FileLocker extends Object
Simple
FileLockwrapper 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(), andunlock()are similar toFileChannel.lock(),FileChannel.tryLock(), andFileLock.release()but with slightly different behaviors. Refer to the corresponding method documentation for more detail.- Since:
- 2.0.0
- Author:
- Pascal Essiembre
-
-
Constructor Summary
Constructors Constructor Description FileLocker(Path lockFile)
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description booleanisLocked()Gets whether the file is locked.voidlock()Locks the unlocked file.voidlock(boolean block)Locks the unlocked file.StringtoString()booleantryLock()Tries to locks the unlocked file and returnstruewhen successful.voidunlock()Unlocks the locked file.
-
-
-
Constructor Detail
-
FileLocker
public FileLocker(Path lockFile)
-
-
Method Detail
-
tryLock
public boolean tryLock() throws IOExceptionTries to locks the unlocked file and returns
truewhen 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 returnsfalse.- Returns:
trueif file was successfully locked.- Throws:
IOException- could not lock- See Also:
lock()
-
lock
public void lock() throws IOExceptionLocks 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.Contrary to
FileChannel.lock(), this method does not block by default. To have it block and wait for a lock to be free, uselock(boolean)withtrueinstead.- Throws:
IOException- could not lock- See Also:
tryLock()
-
lock
public void lock(boolean block) throws IOExceptionLocks 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 totrueto wait for an available lock- Throws:
IOException- could not lock
-
unlock
public void unlock() throws IOExceptionUnlocks 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:
trueif locked.
-
-