Java Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 6.00

Garbage Collection and Unused Objects

This section describes what is garbage collection and what is an unused object.

Garbage Collector: An execution thread that automatically frees up the memory occupied by unused objects. The garbage collector is managed by the JVM and executed separately from the application program main thread that.

Garbage Collection: The process during which the garbage collector actively identifying unused objects, and remove them to frees up the memory.

There are two key questions involved in the garbage collection:

  • How garbage collector identifies objects as unused objects?
  • When garbage collector performs the collection process?

Unused Object: An object that has zero live reference pointing to it. Java does not provide us any facilities to check how many references are there for a given object. But we can read the program source code to figure this out.

For example, after executing the following section of code:

   String a = new String("Apple");
   a = new String("Banana);
   new String("Orange");
   String g = sub("Grape");
   String x = "Kiwi";
   String y = x;
   x = null;
   ...
   static String sub(String b) {
      String l = new String{"Peach");
      return new String("Pear");
   }

objects created by the code will have the following status:

  • String object of "Apple": Unused, because the only reference from "a" is gone now. "a" is pointing to another object now.
  • String object of "Banana": Used, because it is still referred by "a".
  • String object of "Orange": Unused, because it was created, but never referenced by any variables.
  • String object of "Grape": Unused, because the reference from "b" is gone now. "a" is out of scope now after the execution of the method sub().
  • String object of "Peach": Unused, because the reference from "l" is gone now. "l" is out of scope now after the execution of the method sub().
  • String object of "Pear": Used, because the reference returned from the method sub() is in "g" now.
  • String object of "Kiwi": Used, because it is still referred by "y", even the reference from "x" is gone now.

Sections in This Chapter

Garbage Collection and Unused Objects

The Automated Garbage Collection Process

gc() - The Garbage Collection Method

Example Program of Using the gc() Method

Dr. Herong Yang, updated in 2008
Garbage Collection and Unused Objects