Java – lock files when writing files to disk

I have two separate threads F1 and F2 (specifically, two Java. Util. Concurrent. Futuretask instances) running in parallel

F1 does some processing, and then copies the results to an XML file It then repeats these steps until it is irrelevant (many XML files are created) F2 view the F1 output directory, take a file, parse it, and perform some processing on it

This is very effective, except that sometimes F2 gets truncated XML data from a file I mean an incomplete XML in which some XML nodes do not exist The problem is that it is not always reproducible, and the truncated files are not always the same Therefore, I think that when F1 writes a file on disk, F2 is trying to read the same file That's why I sometimes make such mistakes

My question: I wonder if there is any mechanism to lock (or even read) the file F1 is currently writing until it is completely written to disk, so F2 will not be able to read it until the file is unlocked Or any other way to solve my problem will be welcome!

F1writing files in this way:

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 is reading the file in this way:

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);
}

Solution

Because you have filtered in F2 XML file, so convert F1 output to Temp file and rename it to XML as the last step In this way, F2 will ignore the file F1 is making until F1 is completely completed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>