本文详细介绍了自 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 包下找到。

参考

from: https://waylau.com/concise-try-with-resources-jdk9/

在 JDK 9 中更简洁使用 try-with-resources 语句的更多相关文章

  1. php 中更简洁的三元运算符 ?:

    PHP 三元运算符是对参数赋值时候的一个简洁的主要用法. 一个主要的用法: PHP 三元运算符能够让你在一行代码中描述判定代码, 从而替换掉类似以下的代码: <?php if (isset($v ...

  2. Nashorn 在JDK 8中融合Java与JavaScript之力

    从JDK 6开始,Java就已经捆绑了JavaScript引擎,该引擎基于Mozilla的Rhino.该特性允许开发人员将JavaScript代码嵌入到Java中,甚至从嵌入的JavaScript中调 ...

  3. Java 9 揭秘(20. JDK 9中API层次的改变)

    Tips 做一个终身学习的人. 在最后一章内容中,主要介绍以下内容: 下划线作为新关键字 改进使用try-with-resources块的语法 如何在匿名类中使用<>操作符 如何在接口中使 ...

  4. Nashorn——在JDK 8中融合Java与JavaScript之力

      从JDK 6开始,Java就已经捆绑了JavaScript引擎,该引擎基于Mozilla的Rhino.该特性允许开发人员将JavaScript代码嵌入到Java中,甚至从嵌入的JavaScript ...

  5. Nashorn——在JDK 8中融合Java与JavaScript之力--转

    原文地址:http://www.infoq.com/cn/articles/nashorn 从JDK 6开始,Java就已经捆绑了JavaScript引擎,该引擎基于Mozilla的Rhino.该特性 ...

  6. ssm+redis 如何更简洁的利用自定义注解+AOP实现redis缓存

    基于 ssm + maven + redis 使用自定义注解 利用aop基于AspectJ方式 实现redis缓存 如何能更简洁的利用aop实现redis缓存,话不多说,上demo 需求: 数据查询时 ...

  7. 更简洁的 CSS 清理浮动方式

    CSS清理浮动有很多种方式,像使用 br 标签自带的 clear 属,使用元素的 overflow,使用空标签来设置 clear:both 等等.但考虑到兼容问题和语义化的问题,一般我们都会使用如下代 ...

  8. [译]JDK 6 and JDK 7中的subString()方法

    (说明,该文章翻译自The substring() Method in JDK 6 and JDK 7) 在JDK 6 and JDK 7中的substring(int beginIndex, int ...

  9. 了解JDK 6和JDK 7中substring的原理及区别

    substring(int beginIndex, int endIndex)方法在jdk 6和jdk 7中的实现是不同的.了解他们的区别可以帮助你更好的使用他.为简单起见,后文中用substring ...

随机推荐

  1. 怎么去除移动端点击a标签链接时的背景色

    在手机端点击链接时会发现有一个背景色,有时候需要改变这个颜色,或者去除这个颜色,有时候a标签做成按钮时这个颜色的存在会很丑,像这样: 可以通过 -webkit-tap-highlight-color: ...

  2. 升级到AndroidStudio3.2.1的注意事项

    升级到AndroidStudio3.2.1的注意事项     即不用再在二级结构的build.gradle中的compileSdkVersion 28 下声明 buildToolsVersion &q ...

  3. 005.LVM删除

    一 删除LVM步骤 卸载挂载点 移除LV 移除VG 移除PV 删除配置文件 二 卸载挂载点 [root@kauai ~]# umount /dev/vg01/lv01 #先卸载挂载点 三 移除LV [ ...

  4. Xamarin iOS教程之进度条和滚动视图

    Xamarin iOS教程之进度条和滚动视图 Xamarin iOS 进度条 进度条可以看到每一项任务现在的状态.例如在下载的应用程序中有进度条,用户可以很方便的看到当前程序下载了多少,还剩下多少.Q ...

  5. Django Model._meta API

    Model._meta API是Django ORM的核心,它使得lookups.queries.forms.admin这些模块通过每个model类的_meta的属性可以了解每个model的情况. 1 ...

  6. Android之Android WebView常见问题及解决方案汇总

    如有转载,请声明出处: 时之沙: http://blog.csdn.net/t12x3456 Android WebView常见问题解决方案汇总: 就目前而言,如何应对版本的频繁更新呢,又如何灵活多变 ...

  7. GDI 泄漏检测方法

    方法一 1.打开电脑的[任务管理器],选择[进程]页,点击菜单项的[查看]项,选择[选择列]: 2.勾选[GDI对象(J)]即可. 3.此时,用户就可以在进程中看到每个进程对应的GDI对象,每个进程的 ...

  8. 基于ngx_lua的动态服务路由方案

    基于ngx_lua的动态服务路由方案 http://geek.csdn.net/news/detail/131497

  9. LDO current regulator for power LED

    LDO current regulator for power LED Challenge You've got a power LED? Great! Build a flash light! Wh ...

  10. Either, neither, both

    http://speakspeak.com/resources/english-grammar-rules/various-grammar-rules/either-neither-both One ...