gpt4 book ai didi

java - 为什么锁定文件时会发生 OverlappingFileLockException?

转载 作者:行者123 更新时间:2023-11-30 06:31:07 25 4
gpt4 key购买 nike

我尝试锁定一个文件并用下面的代码写入它:

public class TrainSetBuildTask implements Runnable {
private String pathname;
public TrainSetBuildTask(String pathname){
this.pathname = pathname;
}

@Override
public void run() {
try {
String content = "content\n";
//write to a file
FileOutputStream os = new FileOutputStream(new File(pathname), true);
FileChannel channel = os.getChannel();
FileLock lock = channel.tryLock();
if (lock != null) {
ByteBuffer bytes = ByteBuffer.wrap(content.getBytes());
channel.write(bytes);
lock.release();
}
channel.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

并新建两个带有该类实例的线程:

    String pathname = "/home/sjtu123/test.arff";
TrainSetBuildTask task1 = new TrainSetBuildTask(pathname);
Thread t1 = new Thread(task1);
TrainSetBuildTask task2 = new TrainSetBuildTask(pathname);
Thread t2 = new Thread(task2);
t1.start();
t2.start();

然后我收到错误 OverlappingFileLockException。我想知道为什么会发生这种情况,因为我只在每个线程中锁定文件一次?如何修复我的代码?

最佳答案

您不能同时多次锁定同一个文件。您需要使用 java 锁定对象来确保一次只有一个线程尝试锁定文件,或者以其他方式协调线程等待直到没有其他线程正在锁定。

来自manual :

File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.

关于java - 为什么锁定文件时会发生 OverlappingFileLockException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9906161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com