强行调用finalize()不止一次

时间:2017-09-07 04:39:50

标签: java garbage-collection

根据Java Doc,对于任何给定对象,Java虚拟机永远不会多次调用finalize方法。

我正在尝试对新创建的对象调用finalize并保持引用。

// Java program to demonstrate requesting 
// JVM to run Garbage Collector
public class Test
{
    public static void main(String[] args) throws InterruptedException,Throwable
    {
        Test t1 = new Test();
        Test t2 = new Test();
                t1.finalize();
                t1.finalize();
        // Nullifying the reference variable
        t1 = null;

        // requesting JVM for running Garbage Collector
        System.gc();


        // Nullifying the reference variable
        t2 = null;

        // requesting JVM for running Garbage Collector
        Runtime.getRuntime().gc();

    }

    @Override
    // finalize method is called on object once 
    // before garbage collecting it
    protected void finalize() throws Throwable
    {
        System.out.println("Garbage collector called");
        System.out.println("Object garbage collected : " + this);
    }

}

输出是:如下所示:

Garbage collector called
Object garbage collected : Test@232204a1
Garbage collector called
Object garbage collected : Test@232204a1
Garbage collector called
Object garbage collected : Test@232204a1
Garbage collector called
Object garbage collected : Test@6fffd0ea

我无法理解GC的行为如何工作,以及如果我调用finalize()方法会发生什么。

0 个答案:

没有答案