Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 the directories are properly created when it is possible that multiple threads might be trying to create similar file structures?

Thanks

(In my case I will be using this on Android)

like image 567
cottonBallPaws Avatar asked Mar 04 '11 04:03

cottonBallPaws


1 Answers

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.

like image 163
Aaron Digulla Avatar answered Oct 06 '22 00:10

Aaron Digulla