日期:2014-05-20  浏览次数:20731 次

关于JAVA SE 中的finalize()相关问题咨询
//: initialization/TerminationCondition.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;
  }
  protected void finalize() {
    if(checkedOut)
      System.out.println("Error: checked out");
    // Normally, you'll also do this:
    // super.finalize(); // Call the base-class version
  }
}

public class TerminationCondition {
  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();
  }
} /* Output:
Error: checked out
*///:~



求解答:

为何同一段代码,点击运行多次却有不同的运行结果???
finalize函数什么情况下才会被垃圾回收器调用???

Java?SE

------解决方案--------------------
简单地说,当JVM没事干的时候,可能会调用它玩玩。要回收资源,请在fianally块而不是finalize函数中写。
------解决方案--------------------
执行gc的时候,第二个直接new的对象,没有引用,可以被gc,而第一个被novel句柄引用着,无法被gc。
我这边执行,结果都一样的。

不过如果有多个对象要释放,其先后顺序是不确定的。
修改了下例子:


class Book {
    boolean checkedOut = false;
    Book(boolean checkOut) {
      checkedOut = checkOut;
    }
    void checkIn() {