使用Java的FileLock时,让close()自动执行一次lock.release()可以吗?
大多数人都应该知道 close()
还会关闭所有流的使用。
这允许执行以下代码:
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(...)));
...
br.close();
这很好,因为我们不需要对 FileInputStream 的引用并记住关闭它。
但它也适用于 FileLock 吗?
final FileInputStream fis = new FileInputStream(new File("buffer.txt"));
final FileChannel c = fis.getChannel();
final FileLock lock = c.lock(0L, Long.MAX_VALUE, true);
final BufferedReader br = new BufferedReader(new InputStreamReader(fis));
try {
while(br.ready()) {
System.out.println(br.readLine());
}
} finally {
br.close();
}
我已经尝试过这段代码,并且当调用 br.close()
时,锁被正确释放,但是这样做安全吗? Closeable JavaDoc 说,“关闭此流并释放与其关联的所有系统资源。”我可以安全地假设我正在使用 close()
,如 release() 指定的那样锁?
As most should know close()
also closes any streams uses.
This allows the follow code:
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(...)));
...
br.close();
This is nice, since we don't need a reference to FileInputStream
and remember to close it.
But does it also work for FileLock
s?
final FileInputStream fis = new FileInputStream(new File("buffer.txt"));
final FileChannel c = fis.getChannel();
final FileLock lock = c.lock(0L, Long.MAX_VALUE, true);
final BufferedReader br = new BufferedReader(new InputStreamReader(fis));
try {
while(br.ready()) {
System.out.println(br.readLine());
}
} finally {
br.close();
}
I've tried this code and the lock is correctly released when br.close()
is called, but is is safe to do so? The Closeable JavaDoc says, "Closes this stream and releases any system resources associated with it." Am I safe to assume that I am using close()
as specified to release()
the lock?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 JavaDoc:
这是 FileInputStream.close() 的内容,
看起来流上的
close
关闭了释放锁的通道。According to the JavaDoc:
And here are the contents of
FileInputStream.close()
It looks like
close
on the stream closes the channel which releases the lock.是的。
锁取决于文件描述符。 当进程中没有表示文件的文件描述符时,就不会存在与其关联的锁。
Yes.
Locks depend on a file descriptor. When there is no file descriptor representing a file in a process, there wouldn't be a lock associated with it.