调用system.gc()会强迫执行GC,这时所有对象的finalize()都会被调用。若不显示调用system.gc(),则可能有部分对象的finalize()会被调用,部分不被调用,或者都不调用。

解决方案 »

  1.   

    强迫GC运行,首先执行finalize(),让后下一步才释放资源,finalize()可以用作监视作用,标记一下你所关心的东西.
      

  2.   

    我显示调用了 可是结果表明没调用finalize 代码如下
    //: c04:DeathCondition.java
    // Using finalize() to detect an object that 
    // hasn't been properly cleaned up.class Book {
      boolean checkedOut = false;
      Book(boolean checkOut) { 
        checkedOut = checkOut; 
      }
      void checkIn() {
        checkedOut = false;
      }
      public void finalize() {
        if(checkedOut)
          System.out.println("Error: checked out");
      }
    }public class DeathCondition {
      public static void main(String[] args) {
        Book novel = new Book(true);
        // Proper cleanup:
        novel.checkIn();
        // Drop the reference, forget to clean up:
        new Book(true);
        // Force garbage collection & finalization:
        System.gc();
      }
    } ///:~
      

  3.   

    怎么会,我这里输出是Error: checked out,明显调用了,你出了什么问题,在仔细检查一下运行环境。
      

  4.   

    finalize并不可靠,java并不许诺一定会调用他
    jdk 文档如下说
    The Java programming language does not guarantee which thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates. 
    对象无用时,java对此对象标记后,需要线程激活finalize方法,
    Java并不保证线程会调用finalize,但会保证finalize无锁(避免lock掉你的
    线程),而且跑出的uncaught异常会被忽略。After the finalize method has been invoked for an object, no further action is taken until the Java virtual machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, including possible actions by other objects or classes which are ready to be finalized, at which point the object may be discarded. The finalize method is never invoked more than once by a Java virtual machine for any given object. Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.