Finalization.java


import java.io.*;

public class Finalization {
   public static void main (String[] args) throws IOException{
   
      for (int i = 0; i < 10; i++){
         new SubA();
         System.gc();   
      }
         
      System.out.println(BaseA.nProduced + " " + BaseA.nDestroyed);
      System.out.println(BaseA.getLeft() + " Left");
      
      System.in.read();
   }
}

class BaseA {
   static    int nProduced  = 0;
   static    int nDestroyed = 0;
   
   protected int nID;
   
   public BaseA() {
      nID = ++nProduced;
   }
   
   static int getLeft() {
      return nProduced - nDestroyed;
   }
   
   protected void finalize() throws Throwable {
      ++nDestroyed;
      super.finalize();
   }
}

class SubA extends BaseA {
   long[] l; 

   public SubA() {
      l = new long[10000];
      System.out.println(nID + ": produced");
   }
   
   protected void finalize() throws Throwable {
      super.finalize();
      System.out.println(nID + ": destroyed");
   }
}

last updated: 10-15-1999
Copyright © 1999 - 2003 Roseanne Zhang, All Rights Reserved
[ Java certification page] [ SCJP FAQ] [ JavaChina]