try-with-resource
结构的优先规则是什么?这是一个示例(注意:所有提到的类都实现了 Closeable
):
try (Page closeablePage = page;
PipedOutputStream out = outs;
SequenceWriter sequenceWriter = mapper.writer().writeValuesAsArray(out)) {
// do stuff
} finally {
callback.run();
}
回调什么时候运行?我的假设是:
- 关闭
SequenceWriter
- 关闭
PipedOutputStream
- 关闭
页面
- 运行回调
我错了吗?
最佳答案
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/