首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java Finalize方法未调用

Java Finalize方法未调用
EN

Stack Overflow用户
提问于 2018-06-24 23:07:17
回答 1查看 77关注 0票数 1

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

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-06-24 23:08:44

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

此外,finalize方法被调用于其对象正在被垃圾回收的类,这在您的场景中不是这种情况。

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

代码语言:javascript
复制
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();
    }
}

输出:

代码语言:javascript
复制
Inside the constructor
Garbage collector called
Object garbage collected : MyGenerator.Test123@11adfb87
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51011154

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档