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
About java finalize()
Don’t be confused with c/c++, java programmers can never decide the timing of garbage collection.
Official description:
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
finalize()
It only defines the action during recycling, but the specific time to collect is still determined by the garbage collector itself.
Read the javadoc carefully
迷茫2017-04-17 17:59:13
System.gc(); just tells gc to perform a recycling action, but what to recycle is still decided by gc itself
黄舟2017-04-17 17:59:13
The function of System.gc() is only to remind the virtual machine to perform garbage collection. It is up to the virtual machine to decide whether to recycle or not.
You can understand that this action is asynchronous.
ringa_lee2017-04-17 17:59:13
To put it simply, although you actively called System.gc(); whether it will be recycled and when it will be recycled is decided by the garbage collector itself. It has no direct relationship with you. You execute your code, and it Perform its garbage collection.