Java finally关键字以及finalize方法

finally代码块

参考了 https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

  当try代码块退出以后,finally代码块总是执行,即使是unexpected exception发生,但是finally用处不仅仅是在异常处理方面,你可以在finally程序块里写一些cleanup代码,把cleanup代码写在finally块中是个好习惯。

但是如果JVM在执行try-catch代码中推出,finally块可能不执行。同样,如果执行try-catch代码的线程中断或者被杀死,finally块也可能不被执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private List<Integer> list;
private static final int SIZE = 10;
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entered try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
} catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}

  因此在finally块中写合适的代码能防止内存泄漏。

finalize方法

  Java有自动的垃圾回收器,不需要人工回收内存。但是一些文件或者系统资源的句柄有时候需要人工管理,finalize方法将在垃圾回收器清除对象之前调用。但是要注意,最好不要依赖finalize方法做清理工作,因为有可能在程序的执行生命周期中没有发生垃圾回收,垃圾回收发生的时刻是不确定的,所以通常不要指望finalize方法做清理工作。也可以stackoverflow的回答when is the finalize() method called in Java?