package FinalizeTest;
public class Person {
public Person(){
System.out.println("person created");
}
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
System.out.println("gc ");
throw new Exception("no effect");
}
}
package FinalizeTest;
public class MainTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Person per = new Person();
per = null;
System.gc();
System.out.println("hello world");
}
}
输出为
person created
hello world
gc
代码如上所示, 求解释为什么hello world
会在gc之前输出??
PHP中文网2017-04-17 17:59:13
关于java的 finalize()
不要与c/c++混淆了,java程序员从来不能决定垃圾回收的时机。
官方描述:finalize()
不要与c/c++混淆了,java程序员从来不能决定垃圾回收的时机。
官方描述:
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
finalize()
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
finalize()
只是定义了回收时的动作,但具体何时回收仍旧由垃圾回收器自己决定。🎜
🎜仔细看下javadoc🎜ringa_lee2017-04-17 17:59:13
说的简单点就是,虽然你主动调用了System.gc();但是它回不回收和什么时候回收都由垃圾回收器自己来做,它和你没有直接关系,你执行你的代码,它执行它的垃圾回收。