java中關(guān)于資源的使用大家估計(jì)都不陌生,無非就是請求資源,建立連接,讀取資源,關(guān)閉資源幾個(gè)步驟,為了保證資源能夠順利釋放,都是在finally塊中進(jìn)行資源釋放,下面常見的資源訪問實(shí)例:
public static void main(String[] args) { FileInputStream fis = null; try { fis = new FileInputStream(""); } catch (FileNotFoundException e) { e.PRintStackTrace(); } finally { try { if(fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); } } }上面的代碼 ,簡單的功能需要的代碼長且不說,而且不夠優(yōu)雅,在同時(shí)有輸入流輸出流的情況,將會更加復(fù)雜,異常處理難度令人抓狂。 現(xiàn)在我們可以擺脫這種現(xiàn)狀了,java7新語法,提供自動(dòng)關(guān)閉資源的方式,如下
public static void main(String[] args) { try (FileInputStream fis = new FileInputStream("");) { fis.read(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }仔細(xì)看,資源的連接是在try()中,這種新語法支持,凡是實(shí)現(xiàn)接口AutoCloseable的類都可以使用這種方式進(jìn)行資源訪問,并且會自動(dòng)釋放。 下面,我們仔細(xì)分析下,為什么資源會自動(dòng)釋放,我們看下面這段,是新 方式代碼javap后的匯編,我簡單的注釋下:
public static void main(java.lang.String[]); Code: 0: aconst_null 1: astore_1 2: aconst_null 3: astore_2 4: new #16 // class java/io/FileInputStream 7: dup 8: ldc #18 // String 10: invokespecial #20 // Method java/io/FileInputStream."<init>":(Ljava/lang/String;)V 13: astore_3 //將實(shí)例化的FileInputStream對象引入保存到局部變量3中 14: aload_3 //FileInputStream引用入棧 15: invokevirtual #23 // Method java/io/FileInputStream.read:()I 18: pop 19: aload_3 20: ifnull 76 //資源為空,則表示沒有開啟資源,也成功返回 23: aload_3 //如果保存FileInputStream對象引用的變量不為空則關(guān)閉資源 24: invokevirtual #27 // Method java/io/FileInputStream.close:()V 27: goto 76 //成功返回 30: astore_1 //既然上面代碼就能保證成功返回,此處開始的代碼就是異常處理了 31: aload_3 32: ifnull 39 35: aload_3 36: invokevirtual #27 // Method java/io/FileInputStream.close:()V 39: aload_1 40: athrow 41: astore_2 42: aload_1 43: ifnonnull 51 46: aload_2 47: astore_1 48: goto 61 51: aload_1 52: aload_2 53: if_acmpeq 61 56: aload_1 57: aload_2 58: invokevirtual #30 // Method java/lang/Throwable.addSuppressed:(Ljava/lang/Throwable;)V 61: aload_1 62: athrow 63: astore_1 64: aload_1 65: invokevirtual #36 // Method java/io/FileNotFoundException.printStackTrace:()V 68: goto 76 71: astore_1 72: aload_1 73: invokevirtual #41 // Method java/io/IOException.printStackTrace:()V 76: return Exception table: //這是java異常處理的機(jī)制,維護(hù)異常表,根據(jù)表來查詢異常后的跳轉(zhuǎn)代碼。 from to target type 14 19 30 any //當(dāng)資源讀時(shí)異常,跳到30處(內(nèi)存偏移量)繼續(xù)執(zhí)行,可以看到是資源關(guān)閉的處理。 4 41 41 any 0 63 63 Class java/io/FileNotFoundException 0 63 71 Class java/io/IOException分析后發(fā)現(xiàn),新的語法其實(shí)就是一種編譯器優(yōu)化,資源總會關(guān)閉,不管是否發(fā)生異常。人通常會犯錯(cuò),但是編譯器卻不會,所以使用新的方式進(jìn)行資源訪問,能夠避免隱藏的bug,而在java7中絕大多數(shù)的資源訪問都已經(jīng)重新實(shí)現(xiàn)了AutoCloseable接口,包括網(wǎng)絡(luò)訪問socket等,所以基本上可以放心的使用,就算沒實(shí)現(xiàn),編譯器也會快速報(bào)錯(cuò)。
新聞熱點(diǎn)
疑難解答
圖片精選