首頁 > Java > java教程 > 主體

詳細介紹Java中的try-with-resource範例程式碼

黄舟
發布: 2017-03-21 11:08:14
原創
1422 人瀏覽過

背景

眾所周知,所有被開啟的系統資源,例如串流、檔案或Socket連線等,都需要被開發者手動關閉,否則隨著程式的不斷運行,資源外洩將會累積成重大的生產事故。

在Java的江湖中,存在著一種名為finally的功夫,它可以保證當你習武走火入魔之時,還可以做一些自救的操作。在古代,處理資源關閉的程式碼通常寫在finally區塊中。然而,如果你同時開啟了多個資源,那麼將會出現惡夢般的場景:

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程式設計師面對這個問題,竟然微微一笑很傾城地說:「這個我們一點都不用考慮的嘞~ 」:

但是兄弟莫慌!我們可以利用Java 1.7中新增的try-with-resource語法糖來開啟資源,而無需碼農們自己書寫資源來關閉程式碼。媽媽再也不用擔心我把手寫斷掉了!我們用try-with-resource來改寫剛才的範例:

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程式設計師鄙視了!好了,以下將會詳細講解其實作原理以及內部機制。

動手實作

為了能夠配合try-with-resource,資源必須實作AutoClosable介面。這個介面的實作類別需要重寫close方法:

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。為了了解這段程式碼的用意,我們稍微修改一下剛才的範例:我們將剛才的程式碼改回遠古時代手動關閉異常的方式,並且在sendDataclose方法中拋出異常

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

总结

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

以上是詳細介紹Java中的try-with-resource範例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!