本文详细介绍了自 JDK 7 引入的 try-with-resources 语句的原理和用法,以及介绍了 JDK 9 对 try-with-resources 的改进,使得用户可以更加方便、简洁的使用 try-with-resources 语句。

在 JDK 7 之前,资源需要手动关闭。

例如下面一个很常见的文件操作的例子:

Charset charset = Charset.forName("US-ASCII");
String s = ...;
BufferedWriter writer = null;
try {
writer = Files.newBufferedWriter(file, charset);
writer.write(s, 0, s.length());
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
} finally {
if (writer != null) writer.close();
}

在 JDK 7 之前,你一定要牢记在 finally 中执行 close 以释放资源

JDK 7 中的 try-with-resources 介绍

try-with-resources 是 JDK 7 中一个新的异常处理机制,它能够很容易地关闭在 try-catch 语句块中使用的资源。所谓的资源(resource)是指在程序完成后,必须关闭的对象。try-with-resources 语句确保了每个资源在语句结束时关闭。所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源。

例如,我们自定义一个资源类

public class Demo {
public static void main(String[] args) {
try(Resource res = new Resource()) {
res.doSome();
} catch(Exception ex) {
ex.printStackTrace();
}
}
} class Resource implements AutoCloseable {
void doSome() {
System.out.println("do something");
}
@Override
public void close() throws Exception {
System.out.println("resource is closed");
}
}

执行输出如下:

do something
resource is closed

可以看到,资源终止被自动关闭了。

再来看一个例子,是同时关闭多个资源的情况:

public class Main2 {
public static void main(String[] args) {
try(ResourceSome some = new ResourceSome();
ResourceOther other = new ResourceOther()) {
some.doSome();
other.doOther();
} catch(Exception ex) {
ex.printStackTrace();
}
}
} class ResourceSome implements AutoCloseable {
void doSome() {
System.out.println("do something");
}
@Override
public void close() throws Exception {
System.out.println("some resource is closed");
}
} class ResourceOther implements AutoCloseable {
void doOther() {
System.out.println("do other things");
}
@Override
public void close() throws Exception {
System.out.println("other resource is closed");
}
}

最终输出为:

do something
do other things
other resource is closed
some resource is closed

在 try 语句中越是最后使用的资源,越是最早被关闭。

try-with-resources 在 JDK 9 中的改进

作为 Milling Project Coin 的一部分, try-with-resources 声明在 JDK 9 已得到改进。如果你已经有一个资源是 final 或等效于 final 变量,您可以在 try-with-resources 语句中使用该变量,而无需在 try-with-resources 语句中声明一个新变量。

例如,给定资源的声明

// A final resource
final Resource resource1 = new Resource("resource1");
// An effectively final resource
Resource resource2 = new Resource("resource2");

老方法编写代码来管理这些资源是类似的:

// Original try-with-resources statement from JDK 7 or 8
try (Resource r1 = resource1;
Resource r2 = resource2) {
// Use of resource1 and resource 2 through r1 and r2.
}

而新方法可以是

// New and improved try-with-resources statement in JDK 9
try (resource1;
resource2) {
// Use of resource1 and resource 2.
}

看上去简洁很多吧。对 Java 未来的发展信心满满。

愿意尝试 JDK 9 这种新语言特性的可以下载使用 JDK 9 快照。Enjoy!

源码

本章例子的源码,可以在 https://github.com/waylau/essential-java 中 com.waylau.essentialjava.exception.trywithresources 包下找到。

参考

try - with - resource的更多相关文章

  1. Spring resource bundle多语言,单引号format异常

    Spring resource bundle多语言,单引号format异常 前言 十一假期被通知出现大bug,然后发现是多语言翻译问题.法语中有很多单引号,单引号在format的时候出现无法匹配问题. ...

  2. Spring5:@Autowired注解、@Resource注解和@Service注解

    什么是注解 传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事物,这么做有两个缺点: 1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分 ...

  3. 【初探Spring】------Spring IOC(三):初始化过程---Resource定位

    我们知道Spring的IoC起到了一个容器的作用,其中装得都是各种各样的Bean.同时在我们刚刚开始学习Spring的时候都是通过xml文件来定义Bean,Spring会某种方式加载这些xml文件,然 ...

  4. 2000条你应知的WPF小姿势 基础篇<34-39 Unhandled Exceptions和Resource>

    在正文开始之前需要介绍一个人:Sean Sexton. 来自明尼苏达双城的软件工程师.最为出色的是他维护了两个博客:2,000Things You Should Know About C# 和 2,0 ...

  5. 【解决方案】 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userHandler': Injection of resource dependencies failed;

    一个错误会浪费好多青春绳命 鉴于此,为了不让大家也走弯路,分享解决方案. [错误代码提示] StandardWrapper.Throwableorg.springframework.beans.fac ...

  6. AngularJS Resource:与 RESTful API 交互

    REST(表征性状态传输,Representational State Transfer)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格.RESTful风格的设计不仅 ...

  7. 运行nltk示例 Resource u'tokenizers punkt english.pickle' not found解决

    nltk安装完毕后,编写如下示例程序并运行,报Resource u'tokenizers/punkt/english.pickle' not found错误 import nltk sentence ...

  8. Android LayoutInflater.inflate(int resource, ViewGroup root, boolean attachToRoot)的参数理解

    方法inflate(int resource, ViewGroup root, boolean attachToRoot) 中 第一个参数传入布局的资源ID,生成fragment视图,第二个参数是视图 ...

  9. ORA-00054: resource busy and acquire with NOWAIT specified

    删除表时遇到 ORA-00054:资源正忙,要求指定NOWAIT 错误.以前在灾备中心遇到过. 资源被锁定了,没有办法删除. 报错日志:ORA-00054: resource busy and acq ...

  10. angular学习笔记(二十八-附1)-$resource中的资源的方法

    通过$resource获取到的资源,或者是通过$resource实例化的资源,资源本身就拥有了一些方法,$save,$delete,$remove,可以直接调用来保存该资源: 比如有一个$resour ...

随机推荐

  1. AttributeError: 'function' object has no attribute 'as_view'

    我的描述:当我启用jwt_required来进行token验证的时候,我提示错误; 解决方案: 修改前代码: 修改后代码: 多看书.多多了解.多看看世界...

  2. 页面导入导出EXCEL

    引用 using Microsoft.Office.Interop.Excel;using System.Reflection;//反射命名空间using System.IO; protected v ...

  3. WPF MVVM实例三

    在没给大家讲解wpf mwm示例之前先给大家简单说下MVVM理论知识: WPF技术的主要特点是数据驱动UI,所以在使用WPF技术开发的过程中是以数据为核心的,WPF提供了数据绑定机制,当数据发生变化时 ...

  4. TKMybatis

    TKMybatis与Mybatis-plus都是mybatis的扩展,有相同的地方,也有不同的地方. 1.导入坐标 <!--mybatis依赖--> <dependency> ...

  5. oracle 19c 导入 12c ORA-39002 ORA-39358

    直接用19c导出的dmp文件导入到12c,报错: ORA-39002: invalid operation ORA-39358: Export dump file version 19.0.0.0.0 ...

  6. pandas的数据筛选之isin和str.contains函数

    筛选是在平时的工作中使用非常频繁的功能,前文介绍了loc和iloc的筛选方法,现在继续介绍一些筛选的方法.   DataFrame列表 以>,<,==,>=,<=来进行选择(& ...

  7. Git 命令将电脑上的文件上传到 Github

    1.在电脑上安装 Windows 版 Git下载地址:https://git-scm.com/downloads2.使用 Git GUI 生成 SSH Key 3.将 SSH Key 添加到 Gith ...

  8. CF1491C Pekora and Trampoline 题解

    题目链接 ​ 比赛时只想到了 \(\mathcal O(n^3)\) 的暴力做法,官方题解是 \(\mathcal O(n^2)\) ,并且是可以优化为 \(\mathcal O(n)\) 的(贪心+ ...

  9. $nextTick解决Vue组件卸载在加载合并的问题

    情况是这样的,父子组件都是复选框,点击父组件的复选框,子组件的复选框要显示并全选,取消复选框,子组件隐藏.子组件显隐我用的 v-if ,使用created钩子函数来使子组件处于全选状态. 但是出现的问 ...

  10. 大牛带你学会java类加载机制,不要错过,值得收藏!

    很多人对java类加载机制都是非常抗拒的,因为这个太难理解了,但是我们作为一名优秀的java工程师,还是要把java类加载机制研究和学习明白的,因为这对于我们在以后的工作中有很大的帮助,因为它在jav ...