Search code examples
javanio

can any process read the target file when my java process renaming the source file


our portal website will read the json file to display the information. the json file will be generated by jobs wrote by java.

  1. I concerned that if the java progress write the json directly, the website process may get an incomplete file because java process is writing the file.

  2. so I decide to write the information to a temp file, after the temp file is ok, rename to the target file, so the website process will get the complete json file.

  3. but I still concerned when I was renaming the file, can any process read the intermediate status of the target file. Actually, I don't know how java implements the rename action.

my code is like below:

Path source = FileSystems.getDefault().getPath("/data/temp/temp.7z.bak");
Files.move(source, source.resolveSibling("/data/temp/temp.7z"), StandardCopyOption.REPLACE_EXISTING);

Solution

  • You may want to use the ATOMIC_MOVE option in your method call :

    Files.move(source, source.resolveSibling("/data/temp/temp.7z"), StandardCopyOption.ATOMIC_MOVE));
    

    Indeed , the documentation states that

    ATOMIC_MOVE

    The move is performed as an atomic file system operation and all other options are ignored. If the target file exists then it is implementation specific if the existing file is replaced or this method fails by throwing an IOException. If the move cannot be performed as an atomic file system operation then AtomicMoveNotSupportedException is thrown. This can arise, for example, when the target location is on a different FileStore and would require that the file be copied, or target location is associated with a different provider to this object.

    This should guarantee that the file gets moved entirely without intermediate states.

    Note that you will get a AtomicMoveNotSupportedException if such an atomic operation is not possible.