请求并发文件锁处理
//加锁
String fileName = ouId + "-back";
File file = new File("C:/temp/" + fileName);
if (!file.exists()) {
file.createNewFile();
}
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
fileChannel = randomAccessFile.getChannel();
lock = fileChannel.lock();
finally {
if (lock != null) {
try {
lock.release();
lock = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileChannel != null) {
try {
fileChannel.close();
fileChannel = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试用例子
public class MytestMutliThread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("请求");
String resultJson = "";
String ouId = "1024";
if(ouId==null || ouId.trim().equals("")){
resultJson = "[{\"result\":false,\"msg\":\"请确认记录是否存在\"}]";
}
FileChannel fileChannel = null;
FileLock lock = null;
try {
//加锁
String fileName = ouId + "-reBack";
File file = new File("C:/temp/" + fileName);
if (!file.exists()) {
file.createNewFile();
}
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
fileChannel = randomAccessFile.getChannel();
lock = fileChannel.lock();
System.out.println("通过文件锁执行");
} catch (Exception e) {
e.printStackTrace();
resultJson = "[{\"result\":false,\"msg\":\"异常错误\"}]";
}finally {
if (lock != null) {
try {
lock.release();
lock = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileChannel != null) {
try {
fileChannel.close();
fileChannel = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(resultJson);
}
}
执行
ExecutorService service = Executors.newFixedThreadPool(5);//5是线程数
for (int i = 0; i < 5; i++){
service.execute(new MytestMutliThread());//并发5个用户
}
结果