Java Finalize方法未调用

时间:2018-06-24 15:07:17

标签: java garbage-collection 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);
    }
}

1 个答案:

答案 0 :(得分:3)

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@11adfb87