Hy all
Following java code is run under struts action handler ,our system is multiuser environment ,so multiple threads is created to handle the multiple user requests.
File.mkdirs() is not thread safe.
The problem is the way in which the mkdirs() function is implemented. It first tries to check whether each of the parent directories exist, and if a parent directory does not exist, then it is created using the mkdir() function.
suppose two threads try to create the following two directories at the same time
Thread1: "Test/CoreJava/Threads"
Thread2: "Test/CoreJava/Swings"
At here suppose Thread1 attempt to file.mkdirs() , and it will make the directory Test/CoreJava/, at the same time Thread2 also attempt to file.mkdirs() or vise verse.So Thread1 or Thread2 attempt will fail and give the error :Cannot create a file when that file already exists.
Following is our code...
if (!file.exists())
{
try
{
file.mkdirs();
}
catch (Exception e)
{
if (!file.exists())
{
file.mkdirs();
}
}
}
How to resolve the describe situation?pls give the solution to prevent the exception?
Can i put the file.mkdirs() code in synchronize block, if i put the synchronize block then should we get any issue in multi user web based application?
any help will be appreciate.
Thanks & Regards
Yatin Baraiya