Java Reference
In-Depth Information
17.2. A Simple Model
Garbage collection is easier to understand with an explicit model so this
section describes a simple one, but practical garbage collectors are far
more sophisticated. Garbage collection is logically split into two phases:
separating live objects from dead objects and then reclaiming the storage
of the dead ones. Live objects are those that are reachable from running
codethe objects that some action of your code can still potentially use.
Dead objects are the garbage that can be reclaimed.
One obvious model of garbage collection is reference counting: When ob-
ject X references object Y, the system increments a counter on Y, and
when X drops its reference to Y, the system decrements the counter.
When the counter reaches zero, Y is no longer live and can be collected,
which will decrement the counts of any other objects to which Y refers.
Reference counting fails in the face of cycles, in which loops are created
in the references. If X and Y reference each other, neither object's
counter will ever become zero, and so neither X nor Y will ever be collec-
ted, nor will anything to which either object refers, directly or indirectly.
Most garbage collectors do not use reference counting for this and other
reasons.
The simplest model of garbage collection not subject to this problem is
called mark-and-sweep. The name refers to the way the two phases of
garbage collection are implemented. To find which objects are live, the
garbage collector first determines a set of roots that contains the dir-
ectly reachable objects: References in local variables on the stack, for
example, are reachable because you can use those variables to manipu-
late the object. Objects referred to by local variables are therefore clearly
live.
Once a set of roots is determined, the collector will mark the objects
referenced by those roots as reachable. It will then examine references
in each of those objects. If an object referred to by such a reference is
already marked reachable from the first step, it is ignored. Otherwise. the
object is marked reachable and its references are examined. This process
continues until no more reachable objects remain unmarked. After this
 
Search WWH ::




Custom Search