背景
在日常开发中,经常都是手动关闭资源,比如IO流,数据库连接等。如果忘关了就可能造成严重的性能后果。
try-finally带来的问题
1、代码不优雅
手动关闭IO流,特别是使用多个时,finally方法里写的嵌套代码真的是不堪入目,下面看一个例子:
public static void main(String[] args) {
BufferedInputStream inputStream = null;
BufferedOutputStream outputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream("t1.txt"));
outputStream = new BufferedOutputStream(new FileOutputStream("t2.txt"));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
因为要保证inputStream和outputStream都要正常关闭,所以往往会选择嵌套着写。
如果finally写成下面那样:
public static void main(String[] args) {
BufferedInputStream inputStream = null;
BufferedOutputStream outputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream("t1.txt"));
outputStream = new BufferedOutputStream(new FileOutputStream("t2.txt"));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
当inputStream.close(); 出现异常了,就不会再运行?outputStream.close();了,就会一直无法释放资源。
2、异常屏蔽问题
当我们想向上层throws异常时,由于只能抛出一个异常,所以下面例子中,inputStream的异常就被outStream屏蔽了。
public static void main(String[] args) throws Exception {
BufferedInputStream inputStream = null;
BufferedOutputStream outputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream("t1.txt"));
outputStream = new BufferedOutputStream(new FileOutputStream("t2.txt"));
} finally {
try {
inputStream.close();
} finally {
outputStream.close();
}
}
}
控制台只显示outStream的异常:
活用try-with-resource
Java 7后引人 try-with-resources,帮助我们快速解决资源释放。
上述代码使用try-with-resource,是不是优雅了很多!!
public static void main(String[] args) {
try (
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream("t1.txt"));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream("t2.txt"));
) {
} catch (Exception e) {
e.printStackTrace();
}
}
其实try-with-resource的原理就是帮我们自动补全close,下面是编译后的class,和我们try-finally写的是大同小异。
public static void main(String[] args) {
try {
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream("t1.txt"));
try {
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream("t2.txt"));
outputStream.close();
} catch (Throwable var5) {
try {
inputStream.close();
} catch (Throwable var4) {
var5.addSuppressed(var4);
}
throw var5;
}
inputStream.close();
} catch (Exception var6) {
var6.printStackTrace();
}
}
|