Control Flow  «Prev  Next»
Lesson 8Garbage collection
Objective Describe how the Java garbage collector works.

Unreachable objects during Garbage Collection

During the course of a program's execution, it is possible for objects used by the program to become inaccessible to the program. These objects are referred to as unreachable objects. [1] For example, in the following program, the Vector object created in line 5 becomes unreachable at line 9 because it is no longer referenced by any program variables.

import java.util.*;
public class GarbageExample {
 static Vector<String> v1, v2;
  public static void main(String[] args) {
   v1 = new Vector<String>(); // line 5
   v2 = new Vector<String>();
   v1 = v2;
Program Output 

When an object becomes unreachable, it is no longer used by the program and becomes eligible for garbage collection[2].
The Java runtime system uses a process known as garbage collection to recover the memory used by unreachable objects. The Java garbage collector consists of a background thread that is executed by the JVM. This thread monitors the objects that are used by Java programs and identifies when objects become unreachable. When the garbage collector[3] finds an unreachable object, it uses the following process to free the resources used by the object:

  1. If the object has a finalize() method, then the garbage collector invokes the object's finalize() method.
  2. If the object's finalize() method has already been invoked, then the garbage collector permanently deletes the object.

The operation of the garbage collector.
The operation of the garbage collector

The garbage collector is subject to the thread scheduling algorithm of the local operating system, and its actual operation is non-deterministic. This means that you cannot predict the following:
  1. When or if the garbage collector will execute
  2. When or if the garbage collector will identify an object as unreachable
  3. When or if an object will be garbage collected
Non-deterministic: Cannot be predicted or determined.

[1]Unreachable object: An object that is no longer accessible to a program.
[2]Eligible for garbage collection: An object that is unreachable is eligible to be destroyed and have its resources reclaimed by the garbage collector.
[3] Garbage collection: The process by which the memory occupied by unreachable objects is reclaimed.