Class FileLock
- java.lang.Object
-
- com.github.nosan.embedded.cassandra.commons.FileLock
-
- All Implemented Interfaces:
AutoCloseable
public final class FileLock extends Object implements AutoCloseable
Utility class for obtaining an exclusive lock on a file.The
FileLockclass simplifies the process of locking files, allowing controlled access to shared resources in a multi-threaded environment. It uses Java NIO'sFileLockto handle file locks.Usage:
It is recommended to use
FileLockwith a try-with-resources block to ensure that any underlying file resources are properly released:Path lockFile = Path.of("example.lock"); try (FileLock lock = FileLock.of(lockFile)) { if (lock.tryLock(1, TimeUnit.MINUTES)) { // Perform actions while the file is locked } else { // Handle inability to acquire lock } }Note: An instance of this class should not be shared across different threads.
- Since:
- 4.0.0
- Author:
- Dmytro Nosan
-
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidclose()Releases all locks and closes the underlyingFileChannel.static FileLockof(Path file)Creates aFileLockinstance for the specified file.booleantryLock(long timeout, TimeUnit timeUnit)Attempts to acquire an exclusive lock on the file.
-
-
-
Method Detail
-
of
public static FileLock of(Path file) throws IOException
Creates aFileLockinstance for the specified file.The specified file will be opened in write mode with the
StandardOpenOption.CREATEoption to ensure that the file will be created if it does not already exist.- Parameters:
file- the path to the file to lock- Returns:
- a new
FileLockinstance - Throws:
IOException- if an I/O error occurs while opening the fileNullPointerException- if thefileisnull
-
tryLock
public boolean tryLock(long timeout, TimeUnit timeUnit) throws FileLockInterruptionException, IOExceptionAttempts to acquire an exclusive lock on the file.This method tries to acquire a lock on the file within the given timeout period. If the lock is successfully acquired during this time, the method returns
true. Otherwise, it returnsfalseafter the timeout period has elapsed.- Parameters:
timeout- the maximum amount of time to wait for the locktimeUnit- the unit of time for thetimeoutparameter- Returns:
trueif the lock was successfully acquired, otherwisefalse- Throws:
IllegalArgumentException- if thetimeoutis negativeFileLockInterruptionException- if the thread is interrupted while waiting for the lockIOException- if an I/O error occurs while trying to acquire the lockNullPointerException- iftimeUnitisnull
-
close
public void close() throws IOExceptionReleases all locks and closes the underlyingFileChannel.After this method is called, the file associated with this
FileLockwill no longer be locked, and itsFileChannelwill be closed.- Specified by:
closein interfaceAutoCloseable- Throws:
IOException- if an I/O error occurs while closing theFileChannel
-
-