美文网首页
关于System.gc()时的finalize()

关于System.gc()时的finalize()

作者: 极客123 | 来源:发表于2018-10-13 23:01 被阅读0次

/**
 * 运行结果如下:
 * finalize()...
 * is Alieve
 * false
 */

public class TestGC {
    public static TestGC testGC = null;

    public static void main(String[] args) throws InterruptedException {
        testGC = new TestGC();

//第一次去gc(),但testGC结果并未被回收,finalize()方法中存在当前对象this的引用
        testGC = null;
        System.gc();
// finalize()方法优先级低,线程等待0.5秒,进行自救
        Thread.sleep(500);
        if (testGC!=null) testGC.isAlieve();
        else System.out.println(false);


//第二次去gc(),但testGC结果被回收,finalize()方法中存在当前对象this的引用
//但是,在这次gc()的时候,finalize()方法却并没有调用
//任何一个对象的finalize()方法仅会被系统自动调用一次,如果对象面临下一次的回收
//它的finalize()方法不会被再次执行
        testGC = null;
        System.gc();
        // finalize()方法优先级低,线程等待0.5秒,进行自救
        Thread.sleep(500);
        if (testGC!=null) testGC.isAlieve();
        else System.out.println(false);
    }

    public void   isAlieve(){
        System.out.println("is Alieve");
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalize()...");
        TestGC.testGC = this;
    }
}

相关文章

网友评论

      本文标题:关于System.gc()时的finalize()

      本文链接:https://www.haomeiwen.com/subject/vdeaaftx.html