Code Analysis(1)--finalize()方法

  Create a class called Tank that can be filled and emptied, and has a termination condition that it must be empty when the object is cleaned up.Write a finalize() that verifies this termination condition. In main(), test the possible scenarios that can occur whtn your Tank is used.

// initialization/TankTest.java
// TIJ4 Chapter Initialization, Exercise 12, page 177

class Tank {
   int howFull = 0;
   Tank() { this(0); }
   Tank(int fullness) {
      howFull = fullness;        
   }
   void sayHowFull() {
      if(howFull == 0) 
         System.out.println("Tank is empty");
      else 
         System.out.println("Tank filling status = " + howFull);
   }
   void empty() {
      howFull = 0;
   }
   protected void finalize() {
      if(howFull != 0)
         System.out.println("Error: Tank not empty! Its name is " + this);
      // Normally, you'll also do this:
      // super.finalize(); // Call the base-class version
   }
}

public class TankTest {
   public static void main(String[] args) {
      Tank tank1 = new Tank();
      Tank tank2 = new Tank(3);
      Tank tank3 = new Tank(5);
      // Proper cleanup: empty tank before going home
      tank2.empty();
      // Drop the reference, forget to cleanup:
      new Tank(6);
      System.out.println("Check tanks:");
      System.out.println("tank1: " + tank1);
      tank1.sayHowFull();
      System.out.println("tank2: " + tank2);
      tank2.sayHowFull();
      System.out.println("tank3: " + tank3);
      tank3.sayHowFull();
      System.out.println("first forced gc():");
      System.gc();
      // Force finalization on exit but using method
      // deprecated since JDK 1.1:
      System.out.println("try deprecated runFinalizersOnExit(true):");
      System.runFinalizersOnExit(true);
      System.out.println("last forced gc():");
      System.gc();
   }    
}/* Output:
  Check tanks:
  tank1: Tank@c17164
  Tank is empty
  tank2: Tank@1fb8ee3
  Tank is empty
  tank3: Tank@61de33
  Tank filling status = 5
  first forced gc():
  Error: Tank not empty! Tank's name is  Tank@ca0b6
  try deprecated runFinalizersOnExit(true):
  last forced gc():
  Error: Tank not empty! Tank's name is  Tank@61de33
*///:~

    由以上例子可知:在第一次强制垃圾回收时,new Tank(6)产生对象所占用的存储空间无法回收,在使用runFinalizersOnExit(true)方法(已过时,不安全)后new Tank(6)产生对象所占用的存储空间已被回收,但是由于tank3对象不满足回收“终结条件”而未被回收。

    上面的解释似乎有点问题,请高手指正!

posted @ 2010-07-23 17:37  philander  阅读(398)  评论(0编辑  收藏  举报