
Garbage Collection (GC)
Notice that after the main method finishes in the previous example, the main stack area is removed. The result
of this would be that the account and amount variable fall out of scope. When account is out of scope,
nothing is left pointing to the instance of BankAccount. Thus, the object is eligible for garbage collection. In
other object-oriented languages, you are required to track all the objects you create and destroy. When you are
done with an object (directly or indirectly), you must write code to manage memory, that is, get rid of the
unused object. This is a very arduous and error-prone activity, often leading to “memory leaks.”
The Java runtime environment manages memory for you! You never have to destroy an object explicitly or
manage the memory it uses. The Java runtime environment deletes objects when it determines that they are
no longer being used. This process is known as garbage collection. The Java runtime environment’s garbage
collector periodically searches memory for “free” (unreferenced) objects that are no longer needed. When it
finds one, it removes it from the heap. In the example above, an object was no longer referenced because it fell
out of scope, a kind of indirect “de-reference.” In the code below, an object reference can be reused, causing
the original object to be directly de-referenced and therefore subject to garbage collection.
Customer c = new Customer("CID10394");
c = new Customer("CID23511"); //Same reference – different objects
Garbage Collection
Table of Contents
Copyright (c) 2008. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an
online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.
Courseware
Training Resources
Tutorials
Services