Java Finalize 方法不调用



这是一段代码。finalize(( 方法应该在 System.gc(( 命令之后调用,但不是。 有什么建议吗?

class test123{
test123(){
System.out.println("Inside the constructor");
}
}
public class finalizemerthd {
public static void main(String args[]) {
test123 obj1 = new test123();
obj1 = null;
System.gc();
}
protected void finalize() throws Throwable
{
System.out.println("Garbage collector called");
System.out.println("Object garbage collected : " + this);
}
}

System.gc()只请求垃圾回收,不保证垃圾回收。

此外,最终方法被调用其对象的类被垃圾回收,这在您的方案中并非如此。

请在下面找到更新的代码和输出:

class Test123 {
Test123() {
System.out.println("Inside the constructor");
}
@Override
protected void finalize() throws Throwable {
System.out.println("Garbage collector called");
System.out.println("Object garbage collected : " + this);
}
}
public class Finalizemerthd {
public static void main(String args[]) {
Test123 obj1 = new Test123();
obj1 = null;
System.gc();
}
}

输出:

Inside the constructor
Garbage collector called
Object garbage collected : MyGenerator.Test123@11adfb87

最新更新