Java利用文件锁实现进程互斥
备忘
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void main(String[] args) {
FileLock lock;
Paths.get(LOCK_PATH).toFile().mkdir();
try (FileOutputStream fileOutputStream = new FileOutputStream(Paths.get(LOCK_PATH,"lockfile" ).toString(), true)) {
FileChannel channel = fileOutputStream.getChannel();
lock = channel.tryLock();
if (lock == null || !lock.isValid()) {
log.info("正在等待其他进程退出...");
lock = channel.lock();
}
try {
execute(args);
} finally {
lock.release();
}
} catch (Exception e) {
log.error("Fatal Error", e);
}
}
浙公网安备 33010602011771号