【发布时间】:2015-07-15 03:33:59
【问题描述】:
我正在使用属性文件来存储两个变量的计数:
- 传输 ID
- 注册号码
逻辑的作用是:
1) 最初,这两个变量被初始化为 1 并存储在 Sequence.properties 文件中。
2) RegisNumber 将为 1,而每当进行调用时,从 Sequence.properties 文件中获取 TransId 的先前值并递增到1.
要求是:函数executeRegNo()可以同时调用'n'个,所以有可能有'n'个进程访问Sequence.properties 文件。
我的修改: 我试图把 fileLock 。代码如下,
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;
}
我得到的错误是: 该进程无法访问该文件,因为另一个进程已锁定该文件的一部分。
将 FileLock 准确地放在代码中的什么位置?
请帮助解决问题。
提前致谢。
【问题讨论】:
-
改用同步。创建单个同步方法来更新文件并从要更新计数的位置调用它。或者您可以使用 java 中的任何其他同步机制
标签: java multithreading file file-locking filelock