java - try-with-resource vs finally 优先级

标签 java try-with-resources

try-with-resource 结构的优先规则是什么?这是一个示例(注意:所有提到的类都实现了 Closeable):

try (Page closeablePage = page;
     PipedOutputStream out = outs;
     SequenceWriter sequenceWriter = mapper.writer().writeValuesAsArray(out)) {
  // do stuff
} finally {
  callback.run();
}

回调什么时候运行?我的假设是:

  1. 关闭SequenceWriter
  2. 关闭PipedOutputStream
  3. 关闭页面
  4. 运行回调

我错了吗?

最佳答案

finally block 将在所有资源被 try-with-resources 语句关闭后运行。

这是在 JLS 中指定的 section 14.20.3.2 , 引用:

Furthermore, all resources will have been closed (or attempted to be closed) by the time the finally block is executed, in keeping with the intent of the finally keyword.

此外,所有资源都以相反的声明顺序关闭。引用 section 14.20.3 (强调我的):

Resources are closed in the reverse order from that in which they were initialized. A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources. Such an exception is suppressed if an exception was thrown previously by an initializer, the try block, or the closing of a resource.

这意味着你的假设是正确的。

关于java - try-with-resource vs finally 优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32966925/

相关文章:

java - if 和 return 或 while 什么更快最好?

java - Java 7 try-with-resources 的 Clover 检测后编译失败

java - JPA递归延迟加载失败

java - OLTU 能否提供 JWT 作为访问 token

java - 为什么java.lang.AutoCloseable 的close 方法抛出Exception,而java.io.Closeable 的close 方法抛出IOException?

java - 如何在 Java 中关闭隐式流?

java - 尝试使用资源为什么不能修改资源

java - 我可以在后台迭代吗?

java - CompletableFuture 无需阻塞即可获取结果