众所周知,全部被打开的系统资源,好比流、文件或者Socket链接等,都须要被开发者手动关闭,不然随着程序的不断运行,资源泄露将会累积成重大的生产事故。html
在Java的江湖中,存在着一种名为finally的
功夫,它能够保证当你习武走火入魔之时,还能够作一些自救的操做。在远古时代,处理资源关闭的代码一般写在finally
块中。然而,若是你同时打开了多个资源,那么将会出现噩梦般的场景:java
public class Demo { public static void main(String[] args) { BufferedInputStream bin = null; BufferedOutputStream bout = null; try { bin = new BufferedInputStream(new FileInputStream(new File("test.txt"))); bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt"))); int b; while ((b = bin.read()) != -1) { bout.write(b); } } catch (IOException e) { e.printStackTrace(); } finally { if (bin != null) { try { bin.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (bout != null) { try { bout.close(); } catch (IOException e) { e.printStackTrace(); } } } } } } }
Oh My God!!!关闭资源的代码居然比业务代码还要多!!!这是由于,咱们不只须要关闭BufferedInputStream
,还须要保证若是关闭BufferedInputStream
时出现了异常, BufferedOutputStream
也要能被正确地关闭。因此咱们不得不借助finally
中嵌套finally
大法。能够想到,打开的资源越多,finally
中嵌套的将会越深!!!程序员
更为可恶的是,Python程序员面对这个问题,居然微微一笑很倾城地说:“这个咱们一点都不用考虑的嘞~”:oracle
可是兄弟莫慌!咱们能够利用Java 1.7中新增的try-with-resource
语法糖来打开资源,而无需码农们本身书写资源来关闭代码。妈妈不再用担忧我把手写断掉了!咱们用try-with-resource
来改写刚才的例子:ide
public class TryWithResource { public static void main(String[] args) { try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt"))); BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) { int b; while ((b = bin.read()) != -1) { bout.write(b); } } catch (IOException e) { e.printStackTrace(); } } }
是否是很简单?是否是很刺激?不再用被Python程序员鄙视了!好了,下面将会详细讲解其实现原理以及内部机制。code
为了可以配合try-with-resource
,资源必须实现AutoClosable
接口。该接口的实现类须要重写close
方法:htm
public class Connection implements AutoCloseable { public void sendData() { System.out.println("正在发送数据"); } @Override public void close() throws Exception { System.out.println("正在关闭链接"); } }
调用类:接口
public class TryWithResource { public static void main(String[] args) { try (Connection conn = new Connection()) { conn.sendData(); } catch (Exception e) { e.printStackTrace(); } } }
运行后输出结果:资源
正在发送数据 正在关闭链接
经过结果咱们能够看到,close方法被自动调用了。开发
那么这个是怎么作到的呢?我相信聪明的大家必定已经猜到了,其实,这一切都是编译器大神搞的鬼。咱们反编译刚才例子的class文件:
public class TryWithResource { public TryWithResource() { } public static void main(String[] args) { try { Connection e = new Connection(); Throwable var2 = null; try { e.sendData(); } catch (Throwable var12) { var2 = var12; throw var12; } finally { if(e != null) { if(var2 != null) { try { e.close(); } catch (Throwable var11) { var2.addSuppressed(var11); } } else { e.close(); } } } } catch (Exception var14) { var14.printStackTrace(); } } }
看到没,在第15~27行,编译器自动帮咱们生成了finally
块,而且在里面调用了资源的close
方法,因此例子中的close
方法会在运行的时候被执行。
我相信,细心的大家确定又发现了,刚才反编译的代码(第21行)比远古时代写的代码多了一个addSuppressed
。为了了解这段代码的用意,咱们稍微修改一下刚才的例子:咱们将刚才的代码改回远古时代手动关闭异常的方式,而且在sendData
和close
方法中抛出异常:
public class Connection implements AutoCloseable { public void sendData() throws Exception { throw new Exception("send data"); } @Override public void close() throws Exception { throw new MyException("close"); } }
修改main方法:
public class TryWithResource { public static void main(String[] args) { try { test(); } catch (Exception e) { e.printStackTrace(); } } private static void test() throws Exception { Connection conn = null; try { conn = new Connection(); conn.sendData(); } finally { if (conn != null) { conn.close(); } } } }
运行以后咱们发现:
basic.exception.MyException: close at basic.exception.Connection.close(Connection.java:10) at basic.exception.TryWithResource.test(TryWithResource.java:82) at basic.exception.TryWithResource.main(TryWithResource.java:7) ......
好的,问题来了,因为咱们一次只能抛出一个异常,因此在最上层看到的是最后一个抛出的异常——也就是close
方法抛出的MyException
,而sendData
抛出的Exception
被忽略了。这就是所谓的异常屏蔽。因为异常信息的丢失,异常屏蔽可能会致使某些bug变得极其难以发现,程序员们不得不加班加点地找bug,如此毒瘤,怎能不除!幸亏,为了解决这个问题,从Java 1.7开始,大佬们为Throwable
类新增了addSuppressed
方法,支持将一个异常附加到另外一个异常身上,从而避免异常屏蔽。那么被屏蔽的异常信息会经过怎样的格式输出呢?咱们再运行一遍刚才用try-with-resource
包裹的main方法:
java.lang.Exception: send data at basic.exception.Connection.sendData(Connection.java:5) at basic.exception.TryWithResource.main(TryWithResource.java:14) ...... Suppressed: basic.exception.MyException: close at basic.exception.Connection.close(Connection.java:10) at basic.exception.TryWithResource.main(TryWithResource.java:15) ... 5 more
能够看到,异常信息中多了一个Suppressed
的提示,告诉咱们这个异常其实由两个异常组成,MyException
是被Suppressed
的异常。可喜可贺!
在使用try-with-resource
的过程当中,必定须要了解资源的close方法内部的实现逻辑。不然仍是可能会致使资源泄露。
举个例子,在Java BIO中采用了大量的装饰器模式。当调用装饰器的close
方法时,本质上是调用了装饰器内部包裹的流的close
方法。好比:
public class TryWithResource { public static void main(String[] args) { try (FileInputStream fin = new FileInputStream(new File("input.txt")); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(new File("out.txt")))) { byte[] buffer = new byte[4096]; int read; while ((read = fin.read(buffer)) != -1) { out.write(buffer, 0, read); } } catch (IOException e) { e.printStackTrace(); } } }
在上述代码中,咱们从FileInputStream
中读取字节,而且写入到GZIPOutputStream
中。GZIPOutputStream
实际上是FileOutputStream
的装饰器。因为try-with-resource
的特性,实际编译以后的代码会在后面带上finally
代码块,而且在里面调用fin.close()
方法和out.close()
方法。咱们再来看GZIPOutputStream
类的close
方法:
public void close() throws IOException { if (!closed) { finish(); if (usesDefaultDeflater) def.end(); out.close(); closed = true; } }
咱们能够看到,out
变量实际上表明的是被装饰的FileOutputStream
类。在调用out
变量的close
方法以前,GZIPOutputStream
还作了finish
操做,该操做还会继续往FileOutputStream
中写压缩信息,此时若是出现异常,则会out.close()
方法被略过,然而这个才是最底层的资源关闭方法。正确的作法是应该在try-with-resource
中单独声明最底层的资源,保证对应的close
方法必定可以被调用。在刚才的例子中,咱们须要单独声明每一个FileInputStream
以及FileOutputStream
:
public class TryWithResource { public static void main(String[] args) { try (FileInputStream fin = new FileInputStream(new File("input.txt")); FileOutputStream fout = new FileOutputStream(new File("out.txt")); GZIPOutputStream out = new GZIPOutputStream(fout)) { byte[] buffer = new byte[4096]; int read; while ((read = fin.read(buffer)) != -1) { out.write(buffer, 0, read); } } catch (IOException e) { e.printStackTrace(); } } }
因为编译器会自动生成fout.close()
的代码,这样确定可以保证真正的流被关闭。
怎么样,是否是很简单呢