这是一段代码。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);
}
}发布于 2018-06-24 23:08:44
System.gc()只请求收集,不保证垃圾收集。
此外,finalize方法被调用于其对象正在被垃圾回收的类,这在您的场景中不是这种情况。
请在下面找到更新后的代码和输出:
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@11adfb87https://stackoverflow.com/questions/51011154
复制相似问题