Reputation: 321
I am facing issue with File.mkdirs(). I am creating few hundred folders in parallel, but seems like few times, this mkdir() api returns true but folder wasn't really created(java 1.8). I have pasted my sample code below, any ideas?
My Sample code and output is here: https://pastebin.com/aYWDw6JZ It creates folders most of the time but fails sometimes.
public void run() {
// TODO Auto-generated method stub
long randData = (long) (System.currentTimeMillis() + (Math.random() * 100000));
String folderPath = File.separatorChar + "data" + File.separatorChar + "ext" + File.separatorChar + randData;
File testFolder = new File(folderPath);
if (!testFolder.exists()) {
if(testFolder.mkdirs() == false)
System.out.println(System.currentTimeMillis() + ": folder creation failed!");
}
String filename = testFolder + File.separator + "test.txt";
File testFile = new File(filename);
FileOutputStream fileOutputStream = null;
boolean bCreated = false;
try {
//Thread.sleep(1000);
if(testFolder.exists() == false) {
System.out.println("Folder not created!");
System.out.println("Folder: " + testFolder.getAbsolutePath() + " does not exist!");
}else
bCreated = true;
fileOutputStream = new FileOutputStream(testFile);
fileOutputStream.close();
testFile.delete();
testFolder.delete();
//System.out.println("success:" + testFile.getAbsolutePath());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Folder created? " + testFolder + ": " + bCreated);
//back off and see if the folder is really created
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Checking again, " + testFolder.getAbsolutePath() + " created? " + testFolder.exists());
}
}
Output:
java.io.FileNotFoundException: \data\ext\1521045935714\test.txt (The system cannot find the path specified)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
at DiskFolderCreationThread.run(DiskFolderCreationThread.java:30)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Folder created? \data\ext\1521045935714: true
Checking again, C:\data\ext\1521045935714 created? false
Upvotes: 1
Views: 938
Reputation: 321
Just want to update my finding as a solution. I found out that in my application, multiple threads are trying to create folder and if two threads are simultaneously trying to create folder with the same name, I see this mkdirs() behavior, otherwise its fine. I eliminated this condition and make sure the folder names are unique across threads and no issues now.
Upvotes: 1