我有两个并行运行的独立线程 F1 和 F2(准确地说,是 java.util.concurrent.FutureTask 的两个实例)。
F1 做一些处理,然后将结果复制到一个 XML 文件中。然后,它重复这些步骤,直到它无事可做(创建了许多 XML 文件)。F2 在 F1 输出目录中查找,并获取一个文件,对其进行解析,并对其执行一些处理。
这非常有效,只是有时 F2 从文件中获取截断的 XML 数据。我的意思是不完整的 XML,其中不存在某些 XML 节点。问题是它并不总是可复制的,被截断的文件并不总是相同的。因此,我认为当 F1 正在磁盘上写入一个文件时,F2 正在尝试读取同一个文件。这就是为什么有时我会遇到这种错误。
我的问题:我想知道是否有某种机制可以锁定(甚至读取)文件 F1 当前正在写入,直到它完全完成将其写入磁盘,所以 F2 在文件解锁之前将无法读取它. 或者任何其他方式来解决我的问题都将受到欢迎!
F1 以这种方式写入文件:
try {
file = new File("some-file.xml");
FileUtils.writeStringToFile(file, xmlDataAsString);
} catch (IOException ioe) {
LOGGER.error("Error occurred while storing the XML in a file.", ioe);
}
F2 以这种方式读取文件:
private File getNextFileToMap() {
File path = getPath(); // Returns the directory where F1 stores the results...
File[] files = path.listFiles(new FilenameFilter() {
public boolean accept(File file, String name) {
return name.toLowerCase().endsWith(".xml");
}
});
if (files.length > 0) {
return files[0];
}
return null;
}
// Somewhere in my main method of F2
...
f = getNextFileToMap();
Node xmlNode = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
if (doc != null) {
xmlNode = doc.getDocumentElement();
}
} catch (Exception e) {
LOGGER.error("Error while getting the XML from the file " + f.getAbsolutePath(), e);
}