java - 多线程目录创建

标签 java multithreading file

我有一个由尝试创建目录(如果尚未创建)的线程调用的函数。但是,当线程尝试并行调用此方法时,会不断抛出 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/

相关文章:

.net - 在多线程期间共享数据 - 非静态变量可以吗?

python - 在python中同步2个线程

c# - 从文件中获取原始文件名

c++ - 将文件读入缓冲区

java - 如果使用 java.io.Console 类 (netbeans) 如何进行调试

java - 在 gwt 上将小部件设置为 TreeItem

java - 从不同线程检查时,ConcurrentLinkedQueue 大小返回零

java - 文件传输-Java套接字编程

java - 如何使用 Selenium Webdriver 等待元素不可点击?

java - 如何将文本写入Android外部存储上的文件?