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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With