Try-With-Resources

在操作與資源有關的API時,常常有人會忘記做close的動作,而造成memory-leak。而資源相關的API常常會伴隨著check-exception,我的習慣會在finally去做close的動作(可參考此篇)。今天剛好看到同事用了try-with-resource寫法,才知道這種寫法,可以避免掉忘記關閉資源的問題。

以我的例子來示範該如何修改:

    private void close(Closeable closable){
        try {
            if( closable != null )
                closable.close();
        } catch (IOException e) {
            // log
        }
    }
 
    private void load(){
        mProp = new Properties();
        InputStream is = null;
        try {
            is = new FileInputStream(mConfigFilePath);
            mProp.load(is );
        } catch (IOException e) {
            // need to handle ..
        } finally {
            close(is);
        }
    }
使用try-with-resources:
        try( InputStream is = new FileInputStream(mConfigFilePath) ){
    		mProp.load(is);
    	} catch (IOException e) {
            // need to handle ..
        }
需要注意的是,使用這種方式try()內被assign的物件必須實做closable,它在發生exception或正常執行完成都會自動呼叫close。可以自行透過以下程式模擬:
public class TestClosable implements Closeable {
 
	@Override
	public void close() throws IOException {
		System.out.println("close");
	}
 
}
public class TryWithResourcePractice {
 
	@Test
	public void testCatch(){
		try( TestClosable tc = new TestClosable() ){
			System.out.println("gg");
			throw new IOException();
		} catch (IOException e) {
			System.out.println("tt");
		}  finally {
			System.out.println("yy");
		}
    }
 
}