public final class FileLock extends Object implements AutoCloseable
class X {
public void m() {
try(FileLock lock = FileLock.of(lockFile)){
if(lock.tryLock(1, TimeUnit.MINUTES){
// locked
} else {
// not locked
}
}
}}
An instance of this class must not be shared across different threads.| Modifier and Type | Method and Description |
|---|---|
void |
close()
Closes the underlying
FileChannel and releases all locks. |
static FileLock |
of(Path file)
Creates a new
FileLock instance for the specified file. |
boolean |
tryLock(long timeout,
TimeUnit timeUnit)
Acquires an exclusive lock on the file.
|
public static FileLock of(Path file) throws IOException
FileLock instance for the specified file.file - the file that should be lockedFileLockIOException - in the case of I/O errorspublic boolean tryLock(long timeout,
TimeUnit timeUnit)
throws FileLockInterruptionException,
IOException
timeout - the maximum time to waittimeUnit - the time unit of the timeout argumenttrue if lock has been acquired otherwise falseFileLockInterruptionException - If the invoking thread is interrupted while blocked in this methodIOException - If some other I/O error occurspublic void close()
throws IOException
FileChannel and releases all locks.close in interface AutoCloseableIOException - If some other I/O error occursCopyright © 2023. All rights reserved.