Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

When Objects Refer to Other Objects

The ComparableInt32 objects considered in the preceding examples are very simple objects--they contain no references to other objects. Reference counting is an ideal strategy for garbage collecting such objects. But what about objects that refer to other objects? For example, consider the Association class described in Chapter gif which represents a tex2html_wrap_inline67215 pair. We can still use reference counting, provided we count all to an object including references from other objects.

Figure gif (a) illustrates the contents memory following the execution of this statement:

object p = new Association(
    new ComparableComparableInt32(57),
    new ComparableInt32(99));
The reference count of the Association is one, because the variable p refers to it. Similarly, the reference counts of the two ComparableInt32 instances are one because the Association refers to both of them.

   figure30053
Figure: Reference counting when objects refer to other objects.

Suppose we assign the value null to the variable p. As shown in Figure gif (b), the reference count of the association becomes zero--it is now garbage. However, until the Association instance continues to exist until it is garbage collected. And because it still exists, it still refers to the ComparableInt32 objects.

Figure gif (d) shows that the garbage collection process adjusts the reference counts on the objects to which the association refers only when the association is garbage collected. The two ComparableInt32 objects are now unreferenced and can be garbage collected as well.


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.