代码如下
*
01
*
02
*
03
*
04
*
05
*
06
*
07
*
08
*
09
*
10
*
11
*
12
*
13
*
14
*
15
*
16
*
17
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);
}
}
</code>
</pre>
使用上述代码,多进程运行测试文件锁
<br />
表现:
1. windows下,两个进程一个先获取文件锁,进程2则等待1 try-catch段执行完成,才开始运行
2. idea运行到wsl上,两个进程先后进入, 文件锁未生效
<br />
环境版本:
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"
>
>
<br />
相关问题 {#%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98}
--------------------------------------------
1. https://github.com/microsoft/WSL/issues/1927
<br />
<br />