# AutoCloseable接口由來
從AutoCloseable的注釋可知它的出現是為了更好的管理資源,準確說是資源的釋放,當一個資源類實現了該接口close方法,在使用try-catch-resources語法創建的資源拋出異常后,JVM會自動調用close 方法進行資源釋放,當沒有拋出異常正常退出try-block時候也會調用close方法。像數據庫鏈接類Connection,io類InputStream或OutputStream都直接或者間接實現了該接口。
## 使用AutoCloseable之前資源管理方式
~~~
public class Admin {
public static void main(String[] args) {
System.out.println("--------手動關閉------------------");
P p = new P();
try {
p.test();
}catch (Exception e){
e.fillInStackTrace();
}finally {
try {
p.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
static class P implements AutoCloseable{
@Override
public void close() throws Exception {
System.out.println("自動關閉");
}
public void test(){
System.out.println("test方法");
}
}
}
~~~
如上代碼創建了兩個資源,在try-catch-finally的finally里面進行手動進行資源釋放,釋放時候還需要進行catch掉異常,這幾乎是經典資源使用的方式,那么既然資源管理都是一個套路,那么為何不做到規范里面那?所以AutoCloseable誕生了。
## 使用AutoCloseable進行資源管理
~~~
public class Admin {
public static void main(String[] args) {
try (P p = new P()) {
p.test();
} catch (Exception e) {
e.printStackTrace();
}
}
static class P implements AutoCloseable{
@Override
public void close() throws Exception {
System.out.println("自動關閉");
}
public void test(){
System.out.println("test方法");
}
}
}
~~~
* 如上使用jdk1.7新增的try-catch-resources語法在try的()內部創建資源,創建的資源在退出try-block時候會自動調用該資源的close方法。Resource實現了AutoCloseable的close方法:
* 使用try-catch-resources結構無論是否拋出異常在try-block執行完畢后都會調用資源的close方法。
* 使用try-catch-resources結構創建多個資源,try-block執行完畢后調用的close方法的順序與創建資源順序相反
* 使用try-catch-resources結構,try-block塊拋出異常后先執行所有資源(try的()中聲明的)的close方法然后在執行catch里面的代碼然后才是finally.
* 只用在try的()中聲明的資源的close方法才會被調用,并且當對象銷毀的時候close也不會被調用
* 使用try-catch-resources結構,無須顯示調用資源釋放。