← 中文资源

简体中文版本

FileLock 独占锁防重复运行

用 FileChannel.tryLock 给批处理加互斥锁:拿不到立即跳过本次运行,持锁期间独占写入,结束后记得释放,防止任务被并发拉起两份。

阅读英文原文

实现说明

全部逻辑都在类 BatchRunner中。 资源声明在 try-with-resources 头部,任何退出路径都会自动关闭;方法里的 finally 块另行执行自己的清理。

使用要点

  • 每一步打印都带着自己的标签:another process holds the lock, skip this run、exclusive lock: valid=、lock released。

常见问题

运行「FileLock 独占锁防重复运行」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 another process holds the lock, skip this run、exclusive lock: valid=、lock released 这类标签。

核心语句

Files.writeString(lockFile, "run started\n"); // 持锁期间独占写入
lock.release();
Path lockFile = Path.of("batch.lock");
FileLock lock = channel.tryLock();

代码示例

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);
        }
    }
}