Class FileLock
- java.lang.Object
-
- com.github.nosan.embedded.cassandra.commons.FileLock
-
- All Implemented Interfaces:
AutoCloseable
public final class FileLock extends Object implements AutoCloseable
Helper class to lock a file. It is recommended practice to lock a file with a try with resources block, such as:
An instance of this class must not be shared across different threads.class X { public void m() { try(FileLock lock = FileLock.of(lockFile)){ if(lock.tryLock(1, TimeUnit.MINUTES){ // locked } else { // not locked } } }}- Since:
- 4.0.0
- Author:
- Dmytro Nosan
-
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidclose()Closes the underlyingFileChanneland releases all locks.static FileLockof(Path file)Creates a newFileLockinstance for the specified file.booleantryLock(long timeout, TimeUnit timeUnit)Acquires an exclusive lock on the file.
-
-
-
Method Detail
-
of
public static FileLock of(Path file) throws IOException
Creates a newFileLockinstance for the specified file.- Parameters:
file- the file that should be locked- Returns:
- a new
FileLock - Throws:
IOException- in the case of I/O errors
-
tryLock
public boolean tryLock(long timeout, TimeUnit timeUnit) throws FileLockInterruptionException, IOExceptionAcquires an exclusive lock on the file.- Parameters:
timeout- the maximum time to waittimeUnit- the time unit of thetimeoutargument- Returns:
trueif lock has been acquired otherwisefalse- Throws:
FileLockInterruptionException- If the invoking thread is interrupted while blocked in this methodIOException- If some other I/O error occurs
-
close
public void close() throws IOExceptionCloses the underlyingFileChanneland releases all locks.- Specified by:
closein interfaceAutoCloseable- Throws:
IOException- If some other I/O error occurs
-
-