使用Java的FileLock时,让close()自动执行一次lock.release()可以吗?

发布于 2024-07-10 14:58:28 字数 957 浏览 8 评论 0原文

大多数人都应该知道 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 FileLocks?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最近可好 2024-07-17 14:58:28

根据 JavaDoc

在锁定之前它一直有效
通过调用release来释放
方法,通过关闭通道
被用来获取它,或者由
Java虚拟机的终止
机器,以先到者为准。

这是 FileInputStream.close() 的内容,

public void close() throws IOException {
    if (channel != null)
        channel.close();
    close0();
}

看起来流上的 close 关闭了释放锁的通道。

According to the JavaDoc:

It remains valid until the lock is
released by invoking the release
method, by closing the channel that
was used to acquire it, or by the
termination of the Java virtual
machine, whichever comes first.

And here are the contents of FileInputStream.close()

public void close() throws IOException {
    if (channel != null)
        channel.close();
    close0();
}

It looks like close on the stream closes the channel which releases the lock.

清眉祭 2024-07-17 14:58:28

是的。

锁取决于文件描述符。 当进程中没有表示文件的文件描述符时,就不会存在与其关联的锁。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文