ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-06-11 21:48:02  阅读:225  来源: 互联网

标签: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();
}

回调何时运行?我的假设是:

>关闭SequenceWriter
>关闭PipedOutputStream
>关闭页面
>运行回调

我错了吗?

解决方法:

在try-with-resources语句关闭所有资源后,将运行finally块.

这在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-resources
来源: https://codeday.me/bug/20190611/1221486.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有