Skip to main content
IBM 
ShopSupportDownloads
IBM HomeProductsConsultingIndustriesNewsAbout IBM
Java Language EssentialsDownload tutorial zip fileEmail this tutorial to a friend
Main menuSection menuGive feedback on this tutorialPrevious panelNext panel
Course Notes
  


Garbage collection page 25 of 37


One of the really powerful features of the Java(TM) programming language is its memory-management strategy. The Java virtual machine allocates objects on the heap dynamically as requested by the new operator:

Other languages put the burden on the programmer to free these objects when they're no longer needed with an operator such as delete or a library function such as free(). The Java programming language does not provide this functionality for the programmer because the Java runtime environment automatically reclaims the memory for objects that are no longer associated with a reference variable. This memory reclamation process is called garbage collection.

Garbage collection involves (1) keeping a count of all references to each object and (2) periodically reclaiming memory for all objects with a reference count of zero. Garbage collection is an old computing technology; it has been used with several computing languages and with environments such as text editors.

Consider the following method:


...
  void aMethod() {
    Dog dog = new Dog();
    // do something with the instance dog
    ...
  }
... 

dog is a local variable within aMethod(), allocated automatically upon method invocation. The new operation creates an instance of Dog; its memory address is stored in dog; and, its reference count is incremented to 1. When this method finishes/returns, the reference variable dog goes out of scope and the reference count is decremented to 0. At this point, the Dog instance is subject to reclamation by the garbage collector.

Next, consider the following code segment:


...
while (true)
  Dog dog = new Dog();
... 

Each iteration of the while loop (which continues forever) allocates a new instance of Dog, storing the reference in the variable dog and replacing the reference to the Dog instance allocated in the previous iteration. At this point, the previously allocated instance is subject to reclamation by the garbage collector.

The garbage collector automatically runs periodically. You can manually invoke the garbage collector at any time with System.gc().


copyright 1996-2000 Magelang Institute dba jGuru


Main menuSection menuGive feedback on this tutorialPrevious panelNext panel
PrivacyLegalContact