背景
眾所周知,所有被打開的系統(tǒng)資源,比如流、文件或者socket連接等,都需要被開發(fā)者手動(dòng)關(guān)閉,否則隨著程序的不斷運(yùn)行,資源泄露將會(huì)累積成重大的生產(chǎn)事故。
在java的江湖中,存在著一種名為finally的功夫,它可以保證當(dāng)你習(xí)武走火入魔之時(shí),還可以做一些自救的操作。在遠(yuǎn)古時(shí)代,處理資源關(guān)閉的代碼通常寫在finally塊中。然而,如果你同時(shí)打開了多個(gè)資源,那么將會(huì)出現(xiàn)噩夢(mèng)般的場(chǎng)景:
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!!! 關(guān)閉資源的代碼竟然比業(yè)務(wù)代碼還要多 !!!這是因?yàn)椋覀儾粌H需要關(guān)閉 bufferedinputstream
,還需要保證如果關(guān)閉 bufferedinputstream
時(shí)出現(xiàn)了異常, bufferedoutputstream
也要能被正確地關(guān)閉。所以我們不得不借助finally中嵌套finally大法。可以想到,打開的資源越多,finally中嵌套的將會(huì)越深!!!
java 1.7中新增的try-with-resource語(yǔ)法糖來打開資源,而無需碼農(nóng)們自己書寫資源來關(guān)閉代碼。再也不用擔(dān)心我把手寫斷掉了!我們用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(); } } } |
動(dòng)手實(shí)踐
為了能夠配合try-with-resource,資源必須實(shí)現(xiàn) autoclosable
接口。該接口的實(shí)現(xiàn)類需要重寫 close
方法:
1
2
3
4
5
6
7
8
9
|
public class connection implements autocloseable { public void senddata() { system.out.println( "正在發(fā)送數(shù)據(jù)" ); } @override public void close() throws exception { system.out.println( "正在關(guān)閉連接" ); } } |
調(diào)用類:
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(); } } } |
運(yùn)行后輸出結(jié)果:
正在發(fā)送數(shù)據(jù)
正在關(guān)閉連接
原理
那么這個(gè)是怎么做到的呢?我相信聰明的你們一定已經(jīng)猜到了,其實(shí),這一切都是編譯器大神搞的鬼。我們反編譯剛才例子的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(); } } } |
看到?jīng)],在第15~27行,編譯器自動(dòng)幫我們生成了finally塊,并且在里面調(diào)用了資源的close方法,所以例子中的close方法會(huì)在運(yùn)行的時(shí)候被執(zhí)行。
異常屏蔽
細(xì)心的你們肯定又發(fā)現(xiàn)了,剛才反編譯的代碼(第21行)比遠(yuǎn)古時(shí)代寫的代碼多了一個(gè) addsuppressed 。為了了解這段代碼的用意,我們稍微修改一下剛才的例子:我們將剛才的代碼改回遠(yuǎn)古時(shí)代手動(dòng)關(guān)閉異常的方式,并且在 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(); } } } } |
運(yùn)行之后我們發(fā)現(xiàn):
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)
......
好的,問題來了,由于我們一次只能拋出一個(gè)異常,所以在最上層看到的是最后一個(gè)拋出的異常——也就是 close 方法拋出的 myexception ,而 senddata 拋出的 exception 被忽略了。這就是所謂的異常屏蔽。由于異常信息的丟失,異常屏蔽可能會(huì)導(dǎo)致某些bug變得極其難以發(fā)現(xiàn),程序員們不得不加班加點(diǎn)地找bug,如此毒瘤,怎能不除!幸好,為了解決這個(gè)問題,從java 1.7開始,大佬們?yōu)?throwable 類新增了 addsuppressed 方法,支持將一個(gè)異常附加到另一個(gè)異常身上,從而避免異常屏蔽。那么被屏蔽的異常信息會(huì)通過怎樣的格式輸出呢?我們?cè)龠\(yùn)行一遍剛才用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 |
可以看到,異常信息中多了一個(gè) suppressed 的提示,告訴我們這個(gè)異常其實(shí)由兩個(gè)異常組成, myexception 是被suppressed的異常。可喜可賀!
注意事項(xiàng)
在使用try-with-resource的過程中,一定需要了解資源的 close 方法內(nèi)部的實(shí)現(xiàn)邏輯。否則還是可能會(huì)導(dǎo)致資源泄露。
舉個(gè)例子,在java bio中采用了大量的裝飾器模式。當(dāng)調(diào)用裝飾器的 close 方法時(shí),本質(zhì)上是調(diào)用了裝飾器內(nèi)部包裹的流的 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
中讀取字節(jié),并且寫入到 gzipoutputstream
中。 gzipoutputstream
實(shí)際上是 fileoutputstream
的裝飾器。由于try-with-resource的特性,實(shí)際編譯之后的代碼會(huì)在后面帶上finally代碼塊,并且在里面調(diào)用fin.close()方法和out.close()方法。我們?cè)賮砜?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變量實(shí)際上代表的是被裝飾的 fileoutputstream
類。在調(diào)用out變量的 close 方法之前, gzipoutputstream
還做了 finish 操作,該操作還會(huì)繼續(xù)往 fileoutputstream
中寫壓縮信息,此時(shí)如果出現(xiàn)異常,則會(huì) out.close()
方法被略過,然而這個(gè)才是最底層的資源關(guān)閉方法。正確的做法是應(yīng)該在try-with-resource中單獨(dú)聲明最底層的資源,保證對(duì)應(yīng)的 close 方法一定能夠被調(diào)用。在剛才的例子中,我們需要單獨(dú)聲明每個(gè) 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(); } } } |
由于編譯器會(huì)自動(dòng)生成 fout.close() 的代碼,這樣肯定能夠保證真正的流被關(guān)閉。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://juejin.im/post/5c62ba79f265da2de660e91e