I am using property file to store the count of two variables:
- TransId
- RegisNumber
The logic works as :
1) Initially the two variables is initialized to 1 and is stored in the Sequence.properties file.
2) The RegisNumber will be 1 whereas whenever call is made the previous value of TransId is fetched from the Sequence.properties file and is incremented to 1.
The requirement is: 'n' number of calls can be made simultaneously to the function executeRegNo(), so there is possibility of 'n' number of processes accessing the Sequence.properties file at the same time.
Modification done by me : I tried to put fileLock . The code is as follow,
public static String executeRegNo() {
File file=new File("C:/Users/abc/Desktop/Files/GetCount.properties");
Properties properties=new Properties();
FileLock lock=null;
if (!file.exists()) {
try
{
file.createNewFile();
properties.setProperty("TransNum", "0");
properties.setProperty("RegId", "1");
properties.store(new FileOutputStream(file), null);
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
if (file.canRead()) {
try
{
FileChannel fileChannel=new RandomAccessFile(file, "rw").getChannel(); // 1. modified
lock=fileChannel.lock();//2. modified
properties.load(new FileInputStream(file));
}
catch (IOException e)
{
e.printStackTrace();
}
String transId = properties.getProperty("TransNum");
String RegisId = properties.getProperty("RegId");
properties.setProperty("TransNum", String.valueOf(Integer.parseInt(transId) + 1));
properties.setProperty("RegId", String.valueOf(Integer.parseInt(RegisId)));
try
{
properties.store(new FileOutputStream(file), null);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
String RId = properties.getProperty("RegId");
String TId = properties.getProperty("TransNum");
try {
lock.release(); //3. modified
} catch (IOException e) {
e.printStackTrace();
}
DecimalFormat df = new DecimalFormat("00");
String R = String.valueOf(df.format(Integer.parseInt(RId)));
DecimalFormat df1 = new DecimalFormat("0000");
String T = String.valueOf(df1.format(Integer.parseInt(TId)));
return R + T;
}
Error I'm getting is : The process cannot access the file because another process has locked a portion of the file.
Where to exactly put the FileLock in the code?
Kindly help in resolving the issues .
Thanks in advance.