meteor
meteor

Reputation: 2568

Multithreaded Directory Create

I have a function that is invoked by a thread trying to create a directory if its not created already. However FileAlreadyExistsException is thrown constantly when threads try to invoke this method in parallel. Making this method synchronized solves the problem but is there a better way. What is the right way to create directory or skip if directory is already created in a multi-threaded environment?

public void createDir(Path path){
    if (Files.notExists(path)) {
          Files.createDirectory(path);
    }       
}

Upvotes: 2

Views: 2119

Answers (1)

mprivat
mprivat

Reputation: 21902

According to the doc, the "checking and create" function is already coded in Files.createDirectory() and is atomic (i.e. it's thread safe):

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.

So you should just be able to remove the extra existence check:

public void createDir(Path path){
      Files.createDirectory(path);
}

Upvotes: 7

Related Questions