FileLock Exclusive Access Via FileChannel
Guard a batch job against duplicate runs with FileChannel.tryLock: skip when another process holds the lock, release it when the run finishes.
Code
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class BatchRunner {
public static void main(String[] args) throws IOException {
Path lockFile = Path.of("batch.lock");
try (FileChannel channel = FileChannel.open(lockFile,
StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
try {
// tryLock 非阻塞:其他进程持锁时返回 null
FileLock lock = channel.tryLock();
if (lock == null) {
System.out.println("another process holds the lock, skip this run");
return;
}
System.out.println("exclusive lock: valid=" + lock.isValid()
+ " shared=" + lock.isShared());
Files.writeString(lockFile, "run started\n"); // 持锁期间独占写入
lock.release();
System.out.println("lock released");
} catch (OverlappingFileLockException e) {
// 只在同一个 JVM 重复锁同一文件时抛出
System.out.println("this JVM already locks the file");
}
} finally {
Files.deleteIfExists(lockFile);
}
}
}Inside the snippet
FileLock Exclusive Access Via FileChannel is built around the class BatchRunner.
Resources are declared in a try-with-resources header, so they close on every exit path; the finally block in this method runs separately for its own cleanup.
Using it
Running the file prints labeled results such as another process holds the lock, skip this run, exclusive lock: valid=, lock released — each operation’s effect is visible in the output.
Key statements
Files.writeString(lockFile, "run started\n"); // 持锁期间独占写入
lock.release();
Path lockFile = Path.of("batch.lock");
FileLock lock = channel.tryLock();
Interactive Tools for This Topic
FAQ
- What does FileLock Exclusive Access Via FileChannel print when run?
- The script runs standalone; its 4 labeled outputs include `another process holds the lock, skip this run`, `exclusive lock: valid=`, `lock released`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.