背景

众所周知,所有被打开的系统资源,比如流、文件或者Socket连接等,都需要被开发者手动关闭,否则随着程序的不断运行,资源泄露将会累积成重大的生产事故。

在Java的江湖中,存在着一种名为finally的功夫,它可以保证当你习武走火入魔之时,还可以做一些自救的操作。在远古时代,处理资源关闭的代码通常写在finally块中。然而,如果你同时打开了多个资源,那么将会出现噩梦般的场景:

  1. public class Demo {
  2. public static void main(String[] args) {
  3. BufferedInputStream bin = null;
  4. BufferedOutputStream bout = null;
  5. try {
  6. bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
  7. bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")));
  8. int b;
  9. while ((b = bin.read()) != -1) {
  10. bout.write(b);
  11. }
  12. }
  13. catch (IOException e) {
  14. e.printStackTrace();
  15. }
  16. finally {
  17. if (bin != null) {
  18. try {
  19. bin.close();
  20. }
  21. catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. finally {
  25. if (bout != null) {
  26. try {
  27. bout.close();
  28. }
  29. catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }
  34. }
  35. }
  36. }
  37. }

Oh My God!!!关闭资源的代码竟然比业务代码还要多!!!这是因为,我们不仅需要关闭BufferedInputStream,还需要保证如果关闭BufferedInputStream时出现了异常, BufferedOutputStream也要能被正确地关闭。所以我们不得不借助finally中嵌套finally大法。可以想到,打开的资源越多,finally中嵌套的将会越深!!!

更为可恶的是,Python程序员面对这个问题,竟然微微一笑很倾城地说:“这个我们一点都不用考虑的嘞~”:

但是兄弟莫慌!我们可以利用Java 1.7中新增的try-with-resource语法糖来打开资源,而无需码农们自己书写资源来关闭代码。妈妈再也不用担心我把手写断掉了!我们用try-with-resource来改写刚才的例子:

  1. public class TryWithResource {
  2. public static void main(String[] args) {
  3. try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
  4. BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
  5. int b;
  6. while ((b = bin.read()) != -1) {
  7. bout.write(b);
  8. }
  9. }
  10. catch (IOException e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. }

是不是很简单?是不是很刺激?再也不用被Python程序员鄙视了!好了,下面将会详细讲解其实现原理以及内部机制。

动手实践

为了能够配合try-with-resource,资源必须实现AutoClosable接口。该接口的实现类需要重写close方法:

  1. public class Connection implements AutoCloseable {
  2. public void sendData() {
  3. System.out.println("正在发送数据");
  4. }
  5. @Override
  6. public void close() throws Exception {
  7. System.out.println("正在关闭连接");
  8. }
  9. }

调用类:

  1. public class TryWithResource {
  2. public static void main(String[] args) {
  3. try (Connection conn = new Connection()) {
  4. conn.sendData();
  5. }
  6. catch (Exception e) {
  7. e.printStackTrace();
  8. }
  9. }
  10. }

运行后输出结果:

  1. 正在发送数据
  2. 正在关闭连接

通过结果我们可以看到,close方法被自动调用了。

原理

那么这个是怎么做到的呢?我相信聪明的你们一定已经猜到了,其实,这一切都是编译器大神搞的鬼。我们反编译刚才例子的class文件:

  1. public class TryWithResource {
  2. public TryWithResource() {
  3. }
  4. public static void main(String[] args) {
  5. try {
  6. Connection e = new Connection();
  7. Throwable var2 = null;
  8. try {
  9. e.sendData();
  10. } catch (Throwable var12) {
  11. var2 = var12;
  12. throw var12;
  13. } finally {
  14. if(e != null) {
  15. if(var2 != null) {
  16. try {
  17. e.close();
  18. } catch (Throwable var11) {
  19. var2.addSuppressed(var11);
  20. }
  21. } else {
  22. e.close();
  23. }
  24. }
  25. }
  26. } catch (Exception var14) {
  27. var14.printStackTrace();
  28. }
  29. }
  30. }

看到没,在第15~27行,编译器自动帮我们生成了finally块,并且在里面调用了资源的close方法,所以例子中的close方法会在运行的时候被执行。

异常屏蔽

我相信,细心的你们肯定又发现了,刚才反编译的代码(第21行)比远古时代写的代码多了一个addSuppressed。为了了解这段代码的用意,我们稍微修改一下刚才的例子:我们将刚才的代码改回远古时代手动关闭异常的方式,并且在sendDataclose方法中抛出异常:

  1. public class Connection implements AutoCloseable {
  2. public void sendData() throws Exception {
  3. throw new Exception("send data");
  4. }
  5. @Override
  6. public void close() throws Exception {
  7. throw new MyException("close");
  8. }
  9. }

修改main方法:

  1. public class TryWithResource {
  2. public static void main(String[] args) {
  3. try {
  4. test();
  5. }
  6. catch (Exception e) {
  7. e.printStackTrace();
  8. }
  9. }
  10. private static void test() throws Exception {
  11. Connection conn = null;
  12. try {
  13. conn = new Connection();
  14. conn.sendData();
  15. }
  16. finally {
  17. if (conn != null) {
  18. conn.close();
  19. }
  20. }
  21. }
  22. }

运行之后我们发现:

  1. basic.exception.MyException: close
  2. at basic.exception.Connection.close(Connection.java:10)
  3. at basic.exception.TryWithResource.test(TryWithResource.java:82)
  4. at basic.exception.TryWithResource.main(TryWithResource.java:7)
  5. ......

好的,问题来了,由于我们一次只能抛出一个异常,所以在最上层看到的是最后一个抛出的异常——也就是close方法抛出的MyException,而sendData抛出的Exception被忽略了。这就是所谓的异常屏蔽。由于异常信息的丢失,异常屏蔽可能会导致某些bug变得极其难以发现,程序员们不得不加班加点地找bug,如此毒瘤,怎能不除!幸好,为了解决这个问题,从Java 1.7开始,大佬们为Throwable类新增了addSuppressed方法,支持将一个异常附加到另一个异常身上,从而避免异常屏蔽。那么被屏蔽的异常信息会通过怎样的格式输出呢?我们再运行一遍刚才用try-with-resource包裹的main方法:

  1. java.lang.Exception: send data
  2. at basic.exception.Connection.sendData(Connection.java:5)
  3. at basic.exception.TryWithResource.main(TryWithResource.java:14)
  4. ......
  5. Suppressed: basic.exception.MyException: close
  6. at basic.exception.Connection.close(Connection.java:10)
  7. at basic.exception.TryWithResource.main(TryWithResource.java:15)
  8. ... 5 more

可以看到,异常信息中多了一个Suppressed的提示,告诉我们这个异常其实由两个异常组成,MyException是被Suppressed的异常。可喜可贺!

一个小问题

在使用try-with-resource的过程中,一定需要了解资源的close方法内部的实现逻辑。否则还是可能会导致资源泄露。

举个例子,在Java BIO中采用了大量的装饰器模式。当调用装饰器的close方法时,本质上是调用了装饰器内部包裹的流的close方法。比如:

  1. public class TryWithResource {
  2. public static void main(String[] args) {
  3. try (FileInputStream fin = new FileInputStream(new File("input.txt"));
  4. GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(new File("out.txt")))) {
  5. byte[] buffer = new byte[4096];
  6. int read;
  7. while ((read = fin.read(buffer)) != -1) {
  8. out.write(buffer, 0, read);
  9. }
  10. }
  11. catch (IOException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. }

在上述代码中,我们从FileInputStream中读取字节,并且写入到GZIPOutputStream中。GZIPOutputStream实际上是FileOutputStream的装饰器。由于try-with-resource的特性,实际编译之后的代码会在后面带上finally代码块,并且在里面调用fin.close()方法和out.close()方法。我们再来看GZIPOutputStream类的close方法:

  1. public void close() throws IOException {
  2. if (!closed) {
  3. finish();
  4. if (usesDefaultDeflater)
  5. def.end();
  6. out.close();
  7. closed = true;
  8. }
  9. }

我们可以看到,out变量实际上代表的是被装饰的FileOutputStream类。在调用out变量的close方法之前,GZIPOutputStream还做了finish操作,该操作还会继续往FileOutputStream中写压缩信息,此时如果出现异常,则会out.close()方法被略过,然而这个才是最底层的资源关闭方法。正确的做法是应该在try-with-resource中单独声明最底层的资源,保证对应的close方法一定能够被调用。在刚才的例子中,我们需要单独声明每个FileInputStream以及FileOutputStream

  1. public class TryWithResource {
  2. public static void main(String[] args) {
  3. try (FileInputStream fin = new FileInputStream(new File("input.txt"));
  4. FileOutputStream fout = new FileOutputStream(new File("out.txt"));
  5. GZIPOutputStream out = new GZIPOutputStream(fout)) {
  6. byte[] buffer = new byte[4096];
  7. int read;
  8. while ((read = fin.read(buffer)) != -1) {
  9. out.write(buffer, 0, read);
  10. }
  11. }
  12. catch (IOException e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. }

由于编译器会自动生成fout.close()的代码,这样肯定能够保证真正的流被关闭。

总结

怎么样,是不是很简单呢,如果学会了话

参考资料

  1. 官方文档

  2. 详解try-with-resource

from: https://juejin.im/entry/57f73e81bf22ec00647dacd0

深入理解 Java try-with-resource 语法糖的更多相关文章

  1. Java的12个语法糖【转】

    本文转载自公众号  Hollis 原创: 会反编译的 Hollis 侵权删 本文从 Java 编译原理角度,深入字节码及 class 文件,抽丝剥茧,了解 Java 中的语法糖原理及用法,帮助大家在学 ...

  2. Java中部分常见语法糖

    语法糖(Syntactic Sugar),也称糖衣语法,指在计算机语言中添加的某种语法,这种语法对语言本身功能来说没有什么影响,只是为了方便程序员的开发,提高开发效率.说白了,语法糖就是对现有语法的一 ...

  3. Java 语法糖详解

    语法糖 语法糖(Syntactic Sugar),也称糖衣语法,是由英国计算机学家 Peter.J.Landin 发明的一个术语,指在计算机语言中添加的某种语法. 这种语法对语言的功能并没有影响,但是 ...

  4. Hollis原创|不了解这12个语法糖,别说你会Java

    GitHub 2.5k Star 的Java工程师成神之路 ,不来了解一下吗? GitHub 2.5k Star 的Java工程师成神之路 ,真的不来了解一下吗? GitHub 2.5k Star 的 ...

  5. 不了解这12个语法糖,别说你会Java!

    阅读本文大概需要 10 分钟. 作者:Hollis 本文从 Java 编译原理角度,深入字节码及 class 文件,抽丝剥茧,了解 Java 中的语法糖原理及用法,帮助大家在学会如何使用 Java 语 ...

  6. Java中有哪些语法糖?

    不要你写汇编,Java句句是糖 不能同意上面的这句话,要说为什么,首先要定义下面要讲的“语法糖”. 语法糖指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,并没有给语言添加什么新东西,但是 ...

  7. Java中的语法糖

    一.范型 1. C#和Java范型的区别 在C#中范型是切实存在的,List<int>和List<String>就是两种不同的类型,它们在系统运行期间生成,有自己的虚方法表和类 ...

  8. 【Java基础】Java中的语法糖

    目录 Java中的语法糖 switch对String和枚举类的支持 对泛型的支持 包装类型的自动装箱和拆箱 变长方法参数 枚举 内部类 条件编译 断言 数值字面量 for-each try-with- ...

  9. Java 中的语法糖,真甜。

    我把自己以往的文章汇总成为了 Github ,欢迎各位大佬 star https://github.com/crisxuan/bestJavaer 我们在日常开发中经常会使用到诸如泛型.自动拆箱和装箱 ...

  10. Java语法糖详解

    语法糖 语法糖(Syntactic Sugar),也称糖衣语法,是由英国计算机学家 Peter.J.Landin 发明的一个术语,指在计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更 ...

随机推荐

  1. Java连接oracle数据库的两种常用方法

    1. 使用thin连接 由于thin驱动都是纯Java代码,并且使用TCP/IP技术通过java的Socket连接上Oracle数据库,所以thin驱动是与平台无关的,你无需安装Oracle客户端,只 ...

  2. android-----带你一步一步优化ListView(一)

    ListView作为android中最常使用的控件,可以以条目的形式显示大量的数据,经常被用于显示最近联系人列表,对于每一个 Item,均要求adapter的getView方法返回一个View,因此L ...

  3. Oracle数据库错误大全

    ORA-00001: 违反唯一约束条件 (.)ORA-00017: 请求会话以设置跟踪事件ORA-00018: 超出最大会话数ORA-00019: 超出最大会话许可数ORA-00020: 超出最大进程 ...

  4. app中页面滑动,防止a链接误触

    问题 app中list列表,当我们用手滑动屏幕,屏幕上页面内容会快速滚动,不会因为手已经离开了屏幕而滚动停止,突然手触摸暂停,当手指是在a标签上面时,会跳转链接,这对客户体验及其不好 思路 先判断滚动 ...

  5. 洛谷P1099 树网的核

    传送门 80分 $ Floyd $ 树的直径可以通过枚举求出.直径的两个端点$ maxi,maxj $ ,由此可知对于一个点 $ k $ ,如果满足 $ d[maxi][k]+d[k][maxj]== ...

  6. php 中使用include、require、include_once、require_once的区别

    在PHP中,我们经常会通过include.require.include_once.require_once来引用文件,都可以达到引用文件的目的,但他们之间又有哪些区别呢,接一下我们详细的介绍一下 i ...

  7. 父窗口中获取iframe中的元素

    js 在父窗口中获取iframe中的元素 1. 格式:window.frames["iframe的name值"].document.getElementById("ifr ...

  8. 【docker】将容器中数据拷贝到主机

    参考:http://blog.csdn.net/yangzhenping/article/details/43667785 docker cp <containerId>:/file/pa ...

  9. 步步为营-42-通过DataAdapter实现增删查改

    说明:通过DataAdapter或者dataset连接数据库,实现对数据增删改查操作. 以前写过一篇步步为营-23-通过GridView实现增删改 1:SqlDataAdapter  DataTabl ...

  10. 通过T4模板实现代码自动生成

    1:准备.tt模板 using BBFJ.OA.IBLL; using BBFJ.OA.IDAL; using BBFJ.OA.Model; using System; using System.Co ...