Class FileSystemLock
This implementation allows to control the access to external resource between different virtual machines. A file is created to control access, where subsequent tries do not succeed acquiring the lock as long as the file exists.
Warning: This implementation does not have the semantics of a traditional Lock
.
Does not provide memory or visibility guarantees following the JMM.
- Since:
- 15.0
-
Constructor Summary
ConstructorDescriptionFileSystemLock
(Path directory, String name) Creates new instance of the lock. -
Method Summary
-
Constructor Details
-
FileSystemLock
Creates new instance of the lock.Creates a new file in the provided directory utilizing the lock's name.
- Parameters:
directory
- : Root directory to create the lock files.name
- : Uniquely identify the file name. If the names conflict, it means the lock is already held.
-
-
Method Details
-
tryLock
Tries to acquire the global lock.Creates a file in the provided directory with the lock's name. If the file already exists, the lock is held by another instance. The instance is not necessarily in the same virtual machine.
- Returns:
true
if acquired the lock,false
, otherwise.- Throws:
IOException
- See Also:
-
unlock
public void unlock()Unlocks the current instance if holding the global lock.This method only has an effect if the lock is hold by this instance. Effectively, the underlying file is deleted.
-
unsafeLock
Unsafely forces the current instance to hold the lock.This method bypasses the existing lock mechanism to delete the underlying file and acquire ownership over it. Use this method with caution! This method is useful in cases of hard crashes of the virtual machine where the lock was not released prior to shutdown.
- Throws:
IOException
- See Also:
-
isAcquired
public boolean isAcquired()Check whether the current instance holds the global lock.- Returns:
true
in case the lock is held,false
, otherwise.
-
toString
-