Java 7 中的资源尝试?
在 Java 7 的新 Try-with-Resources 语法中,我是否需要担心资源的顺序?
try (InputStream in = loadInput(...); // <--- can these be in any order?
OutputStream out = createOutput(...) ){
copy(in, out);
}
catch (Exception e) {
// Problem reading and writing streams.
// Or problem opening one of them.
// If compound error closing streams occurs, it will be recorded on this exception
// as a "suppressedException".
}
In the new Try-with-Resources syntax in Java 7 do I need to worry about the order of the resources?
try (InputStream in = loadInput(...); // <--- can these be in any order?
OutputStream out = createOutput(...) ){
copy(in, out);
}
catch (Exception e) {
// Problem reading and writing streams.
// Or problem opening one of them.
// If compound error closing streams occurs, it will be recorded on this exception
// as a "suppressedException".
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在您的示例中,顺序绝对不重要。您仅使用 try 块中的资源,其中两者都已可用。
如果您要连接到数据库,顺序或打开很重要,但我会创建一个单独的方法来覆盖它。该方法需要实现AutoClosable并重写close()方法。尽管 close() 会引发异常,但您的方法不必这样做。
In your example, the order definitely doesn't matter. You only use resources in the try block, where both are already available.
If you would be connecting to the database, order or opening matters, but I would create a separate method to cover that. This method needs to implement AutoClosable and override the method close(). Although close() throws an Exception, your method doesn't have to.
实际上顺序根本不重要。理想情况下,如果资源不相关,您可以按任何顺序打开它们,也可以按任何顺序关闭它们。
如果资源是相关的,你必须按照创建它们的顺序,例如首先创建Connection,然后创建PreparedStatement,我没有任何证据,但我认为java以先进先出的顺序关闭资源以避免任何依赖问题。
Actually order doesn't matter at all. Ideally if the resources are un-related, you can open them in any order and they can be closed in any order.
If resources are related, you HAVE to follow the order to create them, for example first create Connection and then PreparedStatement, I don't have any proof but I think java closes resources in FIFO order to avoid any dependencies issue.
如果一个资源的打开依赖于另一个资源的打开,那么这很重要。例如,如果打开 B 需要打开 A,那么您显然会希望先打开 A。另一件需要注意的事情是,资源关闭的顺序与打开的顺序相反。例如,如果您打开 A,然后打开 B,那么当 try-with-resources 关闭它们时,首先关闭 B,然后再关闭 A。
It matters if the opening of a resource depends on another resource being opened. For example, if the opening of B requires A being opened, you would obvious want A opened first. The other thing to attention is that resources are closed in the opposite order they are opened. For example, if you open A and then B, then when try-with-resources closes them, B is closed first followed by A.
当且仅当使用正常的 try {create resources} finally {close resources} 语法时顺序很重要。最先获取的资源将最后关闭。有关详细信息,请参阅技术说明 。
Order matters if and only if it would matter when using the normal try {create resources} finally {close resources} syntax. Resources which were acquired first will be closed last. See the technotes for details.