我需要知道什么时候在JVM中调用finalize()方法。我创建了一个测试类,当finalize()方法被重写时写入文件。它没有被执行。有人能告诉我为什么它不能执行吗?


finalize方法在对象即将被垃圾收集时被调用。这可以在它有资格进行垃圾收集之后的任何时间进行。

注意,完全有可能一个对象永远不会被垃圾收集(因此finalize永远不会被调用)。当对象永远不符合gc条件(因为在JVM的整个生命周期内都可以访问它),或者在对象符合条件到JVM停止运行之间没有实际运行垃圾收集时(这种情况经常发生在简单的测试程序中),就会发生这种情况。

有一些方法可以告诉JVM在尚未调用的对象上运行finalize,但使用这些方法也不是一个好主意(该方法的保证也不是很强)。

如果您依赖finalize来实现应用程序的正确操作,那么您就做错了一些事情。finalize只能用于清理(通常是非java)资源。这正是因为JVM不能保证finalize在任何对象上都被调用。


什么时候在Java中调用finalize()方法?

finalize方法将在GC检测到对象不再可达之后调用,并且在它实际回收对象所使用的内存之前调用。

If an object never becomes unreachable, finalize() will never be called on it. If the GC doesn't run then finalize() may never be called. (Normally, the GC only runs when the JVM decides that there is likely to enough garbage to make it worthwhile.) It may take more than one GC cycle before the GC determines that a specific object is unreachable. (Java GCs are typically "generational" collectors ...) Once the GC detects an object is unreachable and finalizable, it is places on a finalization queue. Finalization typically occurs asynchronously with the normal GC.

(JVM规范实际上允许JVM永远不运行终结器……前提是它不回收对象所使用的空间。以这种方式实现的JVM将是残废的/无用的,但这种行为是“允许的”。)

其结果是,依赖最终确定来完成必须在特定时间框架内完成的事情是不明智的。根本不使用它们是“最佳实践”。应该有更好的(即更可靠的)方法来做你在finalize()方法中试图做的事情。

终结的唯一合法用途是清理应用程序代码丢失的与对象相关的资源。即使这样,您也应该尝试编写应用程序代码,使其在一开始就不会丢失对象。(例如,使用Java 7+ try-with-resources来确保close()总是被调用…)


我创建了一个测试类,当finalize()方法被重写时写入文件。它没有被执行。有人能告诉我为什么它不能执行吗?

这很难说,但有几种可能性:

对象不会被垃圾收集,因为它仍然是可达的。 对象不会被垃圾收集,因为GC在测试结束之前不会运行。 对象由GC找到,并由GC放置在终结队列中,但是在测试结束之前,终结不会完成。


Java finalize()方法不是析构函数,不应用于处理应用程序所依赖的逻辑。Java规范声明,不能保证在应用程序的生存期内调用finalize方法。

你可能想要的是一个finally和cleanup方法的组合,如:

MyClass myObj;

try {
    myObj = new MyClass();

    // ...
} finally {
    if (null != myObj) {
        myObj.cleanup();
    }
}

这将正确处理MyClass()构造函数抛出异常时的情况。


一般来说,最好不要依赖finalize()来做任何清理等。

根据Javadoc(值得一读),它是:

当垃圾回收确定对象不再有引用时,由垃圾回收器在对象上调用。

正如Joachim指出的,如果对象总是可访问的,那么在程序的生命周期中,这可能永远不会发生。

此外,垃圾收集器不保证在任何特定时间运行。一般来说,我想说的是finalize()可能不是最好的方法,除非有特定的事情需要它。


protected void finalize() throws Throwable {} every class inherits the finalize() method from java.lang.Object the method is called by the garbage collector when it determines no more references to the object exist the Object finalize method performs no actions but it may be overridden by any class normally it should be overridden to clean-up non-Java resources ie closing a file if overridding finalize() it is good programming practice to use a try-catch-finally statement and to always call super.finalize(). This is a safety measure to ensure you do not inadvertently miss closing a resource used by the objects calling class protected void finalize() throws Throwable { try { close(); // close open files } finally { super.finalize(); } } any exception thrown by finalize() during garbage collection halts the finalization but is otherwise ignored finalize() is never run more than once on any object

引用自:http://www.janeg.ca/scjp/gc/finalize.html

你也可以看看这篇文章:

对象终结和清理


最终确定方法是不保证的。当对象符合GC条件时调用此方法。在许多情况下,对象可能不会被垃圾收集。


Finalize将打印出类创建的计数。

protected void finalize() throws Throwable {
    System.out.println("Run F" );
    if ( checkedOut)
        System.out.println("Error: Checked out");
        System.out.println("Class Create Count: " + classCreate);
}

main

while ( true) {
    Book novel=new Book(true);
    //System.out.println(novel.checkedOut);
    //Runtime.getRuntime().runFinalization();
    novel.checkIn();
    new Book(true);
    //System.runFinalization();
    System.gc();

如你所见。下面的输出显示了类计数为36时第一次执行的gc。

C:\javaCode\firstClass>java TerminationCondition
Run F
Error: Checked out
Class Create Count: 36
Run F
Error: Checked out
Class Create Count: 48
Run F

An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection. Generally an object becomes eligible for garbage collection in Java on following cases:

该对象的所有引用显式设置为空,例如object = null 对象在块内创建,一旦控件退出该块,引用就会离开作用域。 父对象设置为空,如果一个对象持有另一个对象的引用,并且当您将容器对象的引用设置为空时,子对象或包含对象自动符合垃圾收集的条件。 如果一个对象只有通过WeakHashMap的活动引用,那么它就有资格进行垃圾收集。


查看Effective Java,第2版第27页。 第7项:避免终结词

终结器是不可预测的,通常是危险的,而且通常是不必要的。永远不要在终结器中做任何时间紧迫的事情。从来没有 依赖终结器更新关键持久状态。

要终止一个资源,请使用try-finally:

// try-finally块保证终止方法的执行 Foo Foo =新的Foo(…); 尝试{ //用foo做必须做的事情 ... }最后{ foo.terminate ();//显式终止方法 }


由于JVM调用finalize()方法存在不确定性(不确定被重写的finalize()是否会被执行),为了研究目的,观察finalize()调用时发生的情况的更好方法是通过命令System.gc()强制JVM调用垃圾收集。

具体来说,finalize()在对象不再使用时被调用。但是当我们试图通过创建新对象来调用它时,它的调用是不确定的。因此,为了确定起见,我们创建了一个空对象c,它显然没有未来的用途,因此我们看到对象c的finalize调用。

例子

class Car {

    int maxspeed;

    Car() {
        maxspeed = 70;
    }

    protected void finalize() {

    // Originally finalize method does nothing, but here we override finalize() saying it to print some stmt
    // Calling of finalize is uncertain. Difficult to observe so we force JVM to call it by System.gc(); GarbageCollection

        System.out.println("Called finalize method in class Car...");
    }
}

class Bike {

    int maxspeed;

    Bike() {
        maxspeed = 50;
    }

    protected void finalize() {
        System.out.println("Called finalize method in class Bike...");
    }
}

class Example {

    public static void main(String args[]) {
        Car c = new Car();
        c = null;    // if c weren`t null JVM wouldn't be certain it's cleared or not, null means has no future use or no longer in use hence clears it
        Bike b = new Bike();
        System.gc();    // should clear c, but not b
        for (b.maxspeed = 1; b.maxspeed <= 70; b.maxspeed++) {
            System.out.print("\t" + b.maxspeed);
            if (b.maxspeed > 50) {
                System.out.println("Over Speed. Pls slow down.");
            }
        }
    }
}

输出

    Called finalize method in class Car...
            1       2       3       4       5       6       7       8       9
    10      11      12      13      14      15      16      17      18      19
    20      21      22      23      24      25      26      27      28      29
    30      31      32      33      34      35      36      37      38      39
    40      41      42      43      44      45      46      47      48      49
    50      51Over Speed. Pls slow down.
            52Over Speed. Pls slow down.
            53Over Speed. Pls slow down.
            54Over Speed. Pls slow down.
            55Over Speed. Pls slow down.
            56Over Speed. Pls slow down.
            57Over Speed. Pls slow down.
            58Over Speed. Pls slow down. 
            59Over Speed. Pls slow down.
            60Over Speed. Pls slow down.
            61Over Speed. Pls slow down.
            62Over Speed. Pls slow down.
            63Over Speed. Pls slow down.
            64Over Speed. Pls slow down.
            65Over Speed. Pls slow down.
            66Over Speed. Pls slow down.
            67Over Speed. Pls slow down.
            68Over Speed. Pls slow down.
            69Over Speed. Pls slow down.
            70Over Speed. Pls slow down.

注意:即使打印到70,并且在此之后对象b在程序中没有被使用,也不确定b是否被JVM清除,因为“调用的finalize方法在类Bike…”没有打印。


在最近与终结器方法搏斗之后(为了在测试期间处理连接池),我不得不说终结器缺少很多东西。使用VisualVM来观察以及使用弱引用来跟踪实际的交互,我发现以下事情在Java 8环境中是正确的(Oracle JDK, Ubuntu 15):

Finalize is not called immediately the Finalizer (GC part) individually owns the reference elusively The default Garbage Collector pools unreachable objects Finalize is called in bulk pointing to an implementation detail that there is a certain phase the garbage collector frees the resources. Calling System.gc() often does not result in objects being finalized more often, it just results in the Finalizer getting aware of an unreachable object more rapidly Creating a thread dump almost always result in triggering the finalizer due to high heap overhead during performing the heap dump or some other internal mechanism Finalization seams to be bound by either memory requirements (free up more memory) or by the list of objects being marked for finalization growing of a certain internal limit. So if you have a lot of objects getting finalized the finalization phase will be triggered more often and earlier when compared with only a few There were circumstances a System.gc() triggered a finalize directly but only if the reference was a local and short living. This might be generation related.

最后认为

最后确定方法是不可靠的,但只能用于一件事。您可以确保在垃圾收集之前关闭或释放对象,从而在正确处理涉及生命结束操作的更复杂生命周期的对象时实现故障安全。这是我能想到的一个值得我们去推翻它的原因。


类,在其中重写finalize方法

public class TestClass {    
    public TestClass() {
        System.out.println("constructor");
    }

    public void display() {
        System.out.println("display");
    }
    @Override
    public void finalize() {
        System.out.println("destructor");
    }
}

finalize方法被调用的几率

public class TestGarbageCollection {
    public static void main(String[] args) {
        while (true) {
            TestClass s = new TestClass();
            s.display();
            System.gc();
        }
    }
}

当内存被转储对象重载时,gc将调用finalize方法

运行并查看控制台,在那里你不会发现finalize方法被频繁调用,当内存超载时,finalize方法将被调用。


Java allows objects to implement a method called finalize() that might get called. finalize() method gets called if the garbage collector tries to collect the object. If the garbage collector doesn't run, the method doesn't get called. If the garbage collector fails to collect the object and tries to run it again, the method doesn't get called in the second time. In practice, you are highly unlikely to use it in real projects. Just keep in mind that it might not get called and that it definitely won't be called twice. The finalize() method could run zero or one time. In the following code, finalize() method produces no output when we run it since the program exits before there is any need to run the garbage collector.


试着运行这个程序,以便更好地理解

public class FinalizeTest 
{       
    static {
        System.out.println(Runtime.getRuntime().freeMemory());
    }

    public void run() {
        System.out.println("run");
        System.out.println(Runtime.getRuntime().freeMemory());
    }

     protected void finalize() throws Throwable { 
         System.out.println("finalize");
         while(true)
             break;          
     }

     public static void main(String[] args) {
            for (int i = 0 ; i < 500000 ; i++ ) {
                    new FinalizeTest().run();
            }
     }
}

Sometimes when it is destroyed, an object must make an action. For example, if an object has a non-java resource such as a file handle or a font, you can verify that these resources are released before destroying an object. To manage such situations, java offers a mechanism called "finalizing". By finalizing it, you can define specific actions that occur when an object is about to be removed from the garbage collector. To add a finalizer to a class simply define the finalize() method. Java execution time calls this method whenever it is about to delete an object of that class. Within the finalize method() you specify actions to be performed before destroying an object. The garbage collector is periodically searched for objects that no longer refer to any running state or indirectly any other object with reference. Before an asset is released, the Java runtime calls the finalize() method on the object. The finalize() method has the following general form:

protected void finalize(){
    // This is where the finalization code is entered
}

使用protected关键字,finalize()类之外的代码可以阻止对finalize()的访问。 务必要理解finalize()是在垃圾收集之前调用的。例如,当对象离开作用域时,它不会被调用。这意味着您无法知道finalize()何时或是否将执行。因此,程序必须提供其他方法来释放系统资源或对象使用的其他资源。不应该依赖finalize()来实现程序的正常运行。


Finalize()在垃圾收集之前被调用。当对象超出作用域时,不调用它。这意味着您无法知道finalize()何时甚至是否会执行。

例子:

如果你的程序在垃圾回收发生之前结束,finalize()将不会执行。因此,它应该被用作备份过程,以确保其他资源的正确处理,或用于特殊用途的应用程序,而不是作为您的程序在其正常运行中使用的手段。


正如在https://wiki.sei.cmu.edu/confluence/display/java/MET12-J.+Do+not+use+finalizers上指出的那样,

There is no fixed time at which finalizers must be executed because time of execution depends on the Java Virtual Machine (JVM). The only guarantee is that any finalizer method that executes will do so sometime after the associated object has become unreachable (detected during the first cycle of garbage collection) and sometime before the garbage collector reclaims the associated object's storage (during the garbage collector's second cycle). Execution of an object's finalizer may be delayed for an arbitrarily long time after the object becomes unreachable. Consequently, invoking time-critical functionality such as closing file handles in an object's finalize() method is problematic.


JDK 18的最新消息

根据openjdk 18发布的JEPS 421, finalize()方法的终结和功能将被标记为已弃用(forRemoval=true),这意味着永久删除将在jdk 18之后的某个后续版本中进行。

从jdk 18开始,一个新的命令行选项——finalization=disabled禁用了所有地方的终结机制,甚至是jdk内部的声明。

这也与这里的这个问题有关,因为它被计划删除的原因是它包含的一些主要缺陷。其中一个缺陷是,从一个对象变得不可访问到调用它的终结器之间可能会经过很长一段时间。GC也不能保证任何终结器将被调用,这也是事实。