代码如下
public void writeWithFileLock(File tempFile){
try (FileChannel workPathResourceMd5Lock = new RandomAccessFile(tempFile,"rw").getChannel()) {
log.info("start to lock");
workPathResourceMd5Lock.lock(0, 10, false);
log.info("locked");
workPathResourceMd5Lock.truncate(0);
workPathResourceMd5Lock.write(ByteBuffer.wrap("1111".getBytes(StandardCharsets.UTF_8)));
Thread.sleep(10000);
} catch (Exception ex){
log.error("Error", ex);
}
try {
log.info("finished.{}:{}", tempFile.getAbsolutePath(), FileUtils.readFileToString(tempFile, StandardCharsets.UTF_8));
} catch (IOException e) {
log.error("Error.", e);
}
}
使用上述代码,多进程运行测试文件锁
表现:
windows下,两个进程一个先获取文件锁,进程2则等待1 try-catch段执行完成,才开始运行
idea运行到wsl上,两个进程先后进入,文件锁未生效
环境版本:
wsl1 on windows
Microsoft Windows [版本 10.0.18362.295]
wsl版本
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=20.04
DISTRIB_CODENAME=focal
DISTRIB_DESCRIPTION="Ubuntu 20.04.6 LTS"