好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

深入理解Java基础之try-with-resource语法糖

背景

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

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

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) {

           throw e;

         }

         finally {

           if (bout != null ) {

             try {

               bout.close();

             }

             catch (ioexception e) {

               throw e;

             }

           }

         }

       }

     }

   }

}

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

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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();

     }

   }

}

动手实践

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

?

1

2

3

4

5

6

7

8

9

public class connection implements autocloseable {

   public void senddata() {

     system.out.println( "正在发送数据" );

   }

   @override

   public void close() throws exception {

     system.out.println( "正在关闭连接" );

   }

}

调用类:

?

1

2

3

4

5

6

7

8

9

10

public class trywithresource {

   public static void main(string[] args) {

     try (connection conn = new connection()) {

       conn.senddata();

     }

     catch (exception e) {

       e.printstacktrace();

     }

   }

}

运行后输出结果:

正在发送数据
正在关闭连接

原理

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

package com.codersm.trywithresource;

 

public class trywithresource {

   public trywithresource() {

   }

 

   public static void main(string[] args) {

     try {

       connection conn = new connection();

       throwable var2 = null ;

 

       try {

         conn.senddata();

       } catch (throwable var12) {

         var2 = var12;

         throw var12;

       } finally {

         if (conn != null ) {

           if (var2 != null ) {

             try {

               conn.close();

             } catch (throwable var11) {

               var2.addsuppressed(var11);

             }

           } else {

             conn.close();

           }

         }

 

       }

     } catch (exception var14) {

       var14.printstacktrace();

     }

 

   }

}

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

异常屏蔽

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

?

1

2

3

4

5

6

7

8

9

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方法:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

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方法:

?

1

2

3

4

5

6

7

8

9

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 方法。比如:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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方法:

?

1

2

3

4

5

6

7

8

9

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 :

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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() 的代码,这样肯定能够保证真正的流被关闭。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://juejin.im/post/5c62ba79f265da2de660e91e

查看更多关于深入理解Java基础之try-with-resource语法糖的详细内容...

  阅读:11次