我有一个由尝试创建目录(如果尚未创建)的线程调用的函数。但是,当线程尝试并行调用此方法时,会不断抛出 FileAlreadyExistsException。使此方法同步
解决了问题,但有更好的方法吗?如果目录已在多线程环境中创建,创建目录或跳过的正确方法是什么?
public void createDir(Path path){
if (Files.notExists(path)) {
Files.createDirectory(path);
}
}
最佳答案
根据doc ,“检查和创建”函数已经在 Files.createDirectory()
中编码并且是原子的(即它是线程安全的):
The check for the existence of the file and the creation of the directory if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the directory.
所以你应该能够删除额外的存在检查:
public void createDir(Path path){
Files.createDirectory(path);
}
关于java - 多线程目录创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33681598/