关闭 AutoCloseable 的正确方法 [英] Proper way to close an AutoCloseable

查看:44
本文介绍了关闭 AutoCloseable 的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关闭 OutputStreamServerSocket,或其他实现 AutoCloseable 接口?

我应该使用 try-catch-finally 吗?或者关闭钩子.

解决方案

使用AutoCloseable 实例带有 try-with-resources 块,因此资源可靠关闭,即使抛出异常.

像这样:

 try (OutputStream stream = new ...) {...//使用资源} catch (IOException e) {...//异常处理代码}

您还可以使用一个块(而不是嵌套块)控制多个资源:

试试 (输出流 out1 = ...;输出流 out2 = ...;输入流 in1 = ...;InputStream in2 = ...;){...}

不要使用 try...finally:对于某些边缘情况(需要 抑制异常).

不要使用shutdown-hook:资源很少是真正全局的,这种方法很容易出现竞争风险.try-with-resources 是正确关闭所有 AutoCloseable 资源的推荐方式:两者同时引入 Java,因此它们可以一起工作.

这样做隐式有助于实现(推荐的)规则,即只有负责创建或打开某物的代码负责处理或关闭它:如果一个方法被传递了一个 OutputStream,它应该从不 close() 它.它应该依赖于调用者关闭它.如果您的任何方法都没有显式调用 close(),则保证您的代码永远不会抛出异常(例如 "Socket closed" java.net.SocketException) 因为它试图使用已关闭的资源.

这样做可确保资源恰好关闭一次.请注意,通常多次关闭 AutoCloseable 是不安全的:close() 操作保证是幂等的.

What is the most reliable pattern to follow when closing an OutputStream, ServerSocket, or other object that implements the AutoCloseable interface?

Should I use try-catch-finally? Or a shutdown hook.

解决方案

The correct way to use an AutoCloseable instance is with a try-with-resources block, so the resource is reliably closed even if an exception is thrown.

Like this:

    try (OutputStream stream = new ...) {
       ... // use the resource
    } catch (IOException e) {
        ... // exception handling code
    }

You can also control multiple resources using one block (rather than nested blocks):

try (
     OutputStream out1 = ...;
     OutputStream out2 = ...;
     InputStream in1 = ...;
     InputStream in2 = ...;
) {
     ...
}

Don't use a try...finally block: that will misbehave for some edge cases (the cases that require a suppressed exception).

Don't use a shutdown-hook: resources are rarely truely gloabl, and that approach will be prone to race hazards. try-with-resources is the recommended manner of properly closing all AutoCloseable resources: the two were introduced to Java at the same time so they can work together.

Doing this implicitly helps implement the (recommended) rule that only the code responsible for creating or opening something is responsible for disposing or closing it: if a method is passed an OutputStream, it should never close() it. It should instead rely on the caller closing it. If none of your methods explicitly call close(), your code is guaranteed never to throw an exception (such as a "Socket closed" java.net.SocketException) because it attempts to use a resource that has been closed.

Doing this ensures that the resource is closed precisely once. Beware that in general it is unsafe to close an AutoCloseable more than once: the close() operation is not guaranteed to be idempotent.

这篇关于关闭 AutoCloseable 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆