How to use mkdirs in a thread safe manner in Java?

前端 未结 5 2261
执念已碎
执念已碎 2021-02-14 17:51

After experiencing issues with mkdirs() and poking around the interwebs, I get the impression that there are thread safety issues with mkdirs().

Is there a way to ensure

5条回答
  •  梦谈多话
    2021-02-14 18:50

    I'm not sure if Android supports the concurrent package but here is my take:

    private static Lock fsLock = new ReentrantLock();
    
    private void mkdir( File dir ) throws FileNotFoundException {
    
        if( dir.exists() ) {
            return;
        }
    
        fsLock.lock();
        try {
            if( !dir.exists() ) {
                log.info( "Creating directory {}", dir.getAbsolutePath() );
                if( !dir.mkdirs() ) {
                    throw new FileNotFoundException( "Can't create directory " + dir.getAbsolutePath() );
                }
            }
        } finally {
            fsLock.unlock();
        }
    }
    

    The method returns early if the directory already exists. If it doesn't exist, only one thread will try to create it.

提交回复
热议问题