有没有更好的方法来独家创建和打开文件?
我唯一想到的就是下面的代码片段。重点是创建文件并将其打开以进行独占的写访问。如果该文件存在,则等待它被其他进程删除或超时并抛出异常。
final long MAX_WAIT = 5 * 1000; // 5 seconds
File tmpFile = new File(configuration.getFilePath().getPath()
+ "." + Util.TMP_EXTENSION);
Path path = tmpFile.toPath();
long start = System.currentTimeMillis();
FileChannel channel = null;
while (true) {
try {
channel = FileChannel.open(path, new HashSet(Arrays.asList(
StandardOpenOption.WRITE,
StandardOpenOption.CREATE_NEW)));
break;
} catch (IOException ex) {
if (System.currentTimeMillis() > (start + MAX_WAIT)) {
throw new RuntimeException("Timeout, couldn't create tmp file '"
+ tmpFile.getPath() + "'", ex);
}
try {
Thread.sleep((long) (10 + (Math.random() * 50)));
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
}
FileLock lock = null;
Writer writer = null;
try {
lock = channel.lock();
writer = new BufferedWriter(Channels.newWriter(
channel, configuration.getEncoding()));
//DO REAL WORK HERE
} catch (IOException ex) {
throw new RuntimeException("Couldn't write data", ex);
} finally {
try {
if (writer != null) {
writer.close();
}
if (lock != null && lock.isValid()) {
lock.release();
}
} catch (IOException ex) {}
}
感谢。