GARBAGE COLLECTION AND OBJECT FINALIZATION

CONTENTS

1. Garbage collection
2. Object finalization


1. GARBAGE COLLECTION

Java contains an automatic garbage collector, thus their are no special methods required to destroy objects. Java tracks objects by allocating a reference counter to every object, when this goes "out of scope" this counter is decremented. When the counter becomes zero the object becomes a candidate for garbage collection when the object is "destroyed" and its memory returned to the heap. Garbage collection occurs when:

  1. When the available memory in the heap falls below a predetermined level.
  2. When the class method System.gc() is called.
  3. When the Java system is idle, e.g. waiting for input.


2. OBJECT FINALIZATION

Although garbage collection releases memory held by individual candidate objects, it does not release the other memory resources that an object may hold, for example the garbage collection process does not close input streams. To dothe latter a special finalization instance method, called finalize(), must be created. Finalizers are automatically called before an object is returned to the heap.

Note that with respect to inheritance finalizer methods are not automatically chained. If you have defined a finalize() method in a subclass, this may override a finalize(0 method in a superclass, and as a consequence the finalize() method in the superclass will never get called. To avoid this problem always include the statement:

super.finalize();

as the last statement in the finalizer of the subclass.




Created and maintained by Frans Coenen. Last updated 29 March 2000