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.
Constructor and Description |
---|
FileLocker(Path lockFile) |
Modifier and Type | Method and Description |
---|---|
boolean |
isLocked()
Gets whether the file is locked.
|
void |
lock()
Locks the unlocked file.
|
void |
lock(boolean block)
Locks the unlocked file.
|
boolean |
tryLock()
Tries to locks the unlocked file and returns
true when
successful. |
void |
unlock()
Unlocks the locked file.
|
public FileLocker(Path lockFile)
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
.
true
if file was successfully locked.IOException
- could not locklock()
public void lock() 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
.
Contrary to FileChannel.lock()
, this method does not block
by default. To have it block and wait for a lock to be free,
use lock(boolean)
with true
instead.
IOException
- could not locktryLock()
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
.
block
- set to true
to wait for an available lockIOException
- could not lockpublic void unlock() throws IOException
Unlocks the locked file. Unlocking an inexistent or already unlocked file has no effect.
IOException
- could not unlockpublic boolean isLocked()
true
if locked.Copyright © 2008–2023 Norconex Inc.. All rights reserved.