Previous | Next | Trail Map | Reference Objects | Understanding Garbage Collection

Vanilla Garbage Collection

The garbage collector must determine which objects are in use and which are not, but how does it do this?

An executing JavaTM program consists of a set of threads, each of which is actively executing a set of methods (one having called the next). Each of these methods can have arguments or local variables that are references to objects. These references are said to belong to a root set of references that are immediately accessible to the program. Other references in the root set include static reference variables defined in loaded classes, and references registered through the Java Native Interface (JNI) API. All objects referenced by this root set of references are said to be reachable by the program in its current state and must not be collected. Also, those objects might contain references to still other objects, which are also reachable, and so on.

All other objects on the heap are considered unreachable, and all unreachable objects are eligible for garbage collection. If an unreachable object has a finalize method, arrangements are made for the object's finalizer to be called. Unreachable objects with no finalizers and objects whose finalizers have been called are simply reclaimed during garbage collection.

Garbage collection algorithms vary, but they all identify the objects that are reachable from the root set and reclaim the space occupied by any other objects. The following diagram is a simplified view of memory in which objects inside the square are reachable from the root set, while objects outside the square are not.

An object may refer to reachable objects and still be unreachable itself. Likewise, an object can be unreachable in spite of references to it, if those references are all from unreachable objects.


Conservative Garbage Collection: If you use Java Native Interface (JNI) to make C calls, the garbage collector might see something in memory created by the C code that looks like a pointer, but is actually garbage. In this case, the memory is not garbage collected because the Java VM is conservative and does not reclaim memory that looks like it could be allocated to a pointer.


Previous | Next | Trail Map | Reference Objects | Understanding Garbage Collection