Class FileLocker
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
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
FileLocker
-
-
Method Details
-
tryLock
Tries 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
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.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:
-
lock
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 totrueto wait for an available lock- Throws:
IOException- could not lock
-
unlock
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:
trueif locked.
-