【发布时间】:2016-09-01 08:57:24
【问题描述】:
我有一种写入文件的方法。我需要同步文件对象
class MessageFile{
public static final String fileName="Main.html"
@AutoWired
AppConifg appconfig;
public boolean writeToFile(String fileContent) throws Exception{
String path = appConfig.getNewsPath() + File.separator + fileName; // getNewsPath is non-static method
final File alertFile= new File(path);
FileOutputStream out = null;
synchronized (alertFile) {
if (!alertFile.exists()) {
alertFile.createNewFile();
}
try {
out = new FileOutputStream(alertFile, false);
out.write(fileContent.getBytes());
out.flush();
} finally {
if (out != null) {
out.close();
}
}
}
return true;
}
}
但是上面的代码不会对文件对象采取锁排他锁,因为这个类的另一个实例可以锁定这个类并写入文件。 所以我想怎么处理这个案子? 我找到了一种解决方法,创建一个附加时间戳的临时文件名(因此临时文件名将始终是唯一的),在向其写入内容后,将首先删除原始文件,然后将临时文件重命名为原始文件名。
【问题讨论】:
-
您的问题不清楚。为什么不能使用排他锁?
标签: java multithreading synchronization