Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
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 which represents a pair. We can still use reference counting, provided we count all to an object including references from other objects.
Figure (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.
Figure: Reference counting when objects refer to other objects.
Suppose we assign the value null to the variable p. As shown in Figure (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 (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.