本来同步至 http://www.waylau.com/concise-try-with-resources-jdk9/html
本文详细介绍了自 JDK 7 引入的 try-with-resources 语句的原理和用法,以及介绍了 JDK 9 对 try-with-resources 的改进,使得用户能够更加方便、简洁的使用 try-with-resources 语句。java
例以下面一个很常见的文件操做的例子:git
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 以释放资源github
try-with-resources 是 JDK 7 中一个新的异常处理机制,它可以很容易地关闭在 try-catch 语句块中使用的资源。所谓的资源(resource)是指在程序完成后,必须关闭的对象。try-with-resources 语句确保了每一个资源在语句结束时关闭。全部实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的全部对象),可使用做为资源。编程
例如,咱们自定义一个资源类api
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"); } }
执行输出以下:oracle
do something resource is closed
能够看到,资源终止被自动关闭了。ide
再来看一个例子,是同时关闭多个资源的状况:ui
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"); } }
最终输出为:.net
do something do other things other resource is closed some resource is closed
在 try 语句中越是最后使用的资源,越是最先被关闭。
做为 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
包下找到。