I was wondering is there any way to update the symlink target without delete the old symlink.
I have two pieces of code, which happens at same time. The first piece is downloading some data every hour and store it in /some/directory
, and it will also create a symlink /most/recent/data
point to the newly downloaded data.
The second piece will read the most recent data from symlink /most/recent/data
.
Below is my current implementation for creating symlink. But the problem is if we delete the original symlink, it will cause problem if we read from it at the same time. Is there any way to update the symlink target without deleting the old symlink?
private void createSymLink(String symLinkPath, Path basePath) {
try {
Files.deleteIfExists(Paths.get(symLinkPath));
Files.createSymbolicLink(Paths.get(symLinkPath), basePath);
} catch (IOException e) {
}
}
I think I just found some possible solution. Create a tmp symlink, and then move it to the old one. Because move is a atomic operation, so the symlink update will be atomic too.
private void createSymLink(String symLinkPath, Path basePath) {
try {
String tmpLink = "/tmp/tmpdir";
Files.createSymbolicLink(Paths.get(tmpLink), basePath);
Files.move(Paths.get(tmpLink), Paths.get(symLinkPath), ATOMIC_MOVE);
} catch (IOException e) {
}
}