Try finally的一个实验和为什么避免重载 finalize()方法--例子

public class TryFinallTest {

public TryFinallTest(){

}
public void runSomething(String str){
System.out.println(str);
}

public static void typeOne(){

TryFinallTest one = new TryFinallTest();
try{
one.runSomething("runing something");
return;
}finally{
one.runSomething("do final work");
}
}
public static void main(String[] args){

TryFinallTest.typeOne();
}
}
输出结果:
runing something
do final work
也就是,只要存在try finally,那么,finally包围的语句块一定会执行。
 
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<<effectiva Java>>中提到,避免使用finalize方法来执行资源清理工作,避免使用finallize方法。
那么,为什么?
例子1:
public class TryCatchFinallyTest implements Runnable {

private void testMethod() throws InterruptedException {
try {
System.out.println("In try block");
throw new NullPointerException();
} catch (NullPointerException npe) {
System.out.println("In catch block");
} finally {
System.out.println("In finally block");
}
}

@Override
protected void finalize() throws Throwable {
System.out.println("In finalize block");
super.finalize();
}

@Override
public void run() {
try {
testMethod();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

////////////////////////////////
public class TestMain2 {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
new Thread(new TryCatchFinallyTest()).start();
}
}
}
输出结果:
In try block
In try block
In catch block
In finally block
In catch block
In finally block
In try block
In catch block
In finally block
 
我们是期望,finalize方法会被执行的。但是,finalize方法没有被执行。finalize方法,是在该对象被GC回收的时候,被GC调用执行的,而我们不知道GC什么时候进行垃圾回收。
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
 
面对这种,依赖于GC,依赖于GC的回收才执行的方法,除非,你真的有需要,否则,我也觉得,不要使用。
 
引用:
原文地址:https://www.cnblogs.com/ttylinux/p/6537009.html