Garbage Collection

 With the help of this section you should be able to:

1.      State the behaviour that is guaranteed by the garbage collection system.

2.      Write code that explicitly makes objects eligible for garbage collection.

3.      Recognise the point in a piece of source code at which an object becomes eligible for garbage collection.

 

Garbage Collection

In Java™, allocation of data storage is done directly when you create an object with the new operation and indirectly when you call a method that has local variables or arguments.

 

Java™ technologys Garbage collection is complex. In this section I am only giving a brief overview of Garbage Collection. Java™ supports automatic garbage collection. This means that the programmer does not need to free the memory used by objects. Java(TM) technology’s runtime environment can claim the memory from the objects that are no longer in use.

Objects that are not being referred become candidates for garbage collection. It is important to note that these objects are candidates only. Java™ technology does not guarantee that garbage collection would happen on these objects. Before actually freeing up the memory, garbage collector invokes the finalize() method of the Object being freed.

The System.gc() method can be invoked by the program to suggest to Java™ technology that the Garbage Collector be invoked. However there is no guarantee when the garbage collection would be invoked. There is also no guarantee on the order in which the objects will be garbage collected.

The example illustrates when a String Object becomes available for Garbage Collection.

public class GCTest

{

     public static void main(String[] args)

     {

          String a, b;

          String c = new String(“Test”);

          a = c;

          c = null;

 

// The string “Test” is not yet available for GC as String a still points to “Test”

         

b = new String(“xyz”);

          b = c;

 

// String “xyz” is now available for GC

         

a = null;

 

// String “Test” is now available for GC

 

     }//end of main method

}//end of GCTest class

 

 

 

 

back