Home>

Java technology allows the finalize () method to do the necessary cleanup before the garbage collector clears objects from memory,This method is called by the garbage collector when it determines that the object is not referenced.

finalize method use case

package test;
class testgc {
  private string str="hello";
  testgc (string str) {
    this.str=str;
  }
  public void finalize () {
    system.out.println (str);
  }
}
public class hello {
  /**
   * @param args
   * /
  public static void main (string [] args) {
    //todo automatically generates method stubs
    system.out.println ("hello");
    testgc test=new testgc ("test1");
    test=new testgc ("test2");
    test=null;//Comment out this sentence,test1 is recycled. Plus, recycle test2 first, then test1
    system.gc ();
  }
}

The finalize () method is defined in the object class,So all classes inherit it.Subclasses override the finalize () method to organize system resources or perform other cleanup work.The finalize () method is called on the object before it is deleted by the garbage collector.

  • Previous JavaScript multiple image upload case
  • Next Four very useful PHP functions