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

When Objects Refer to Other Objects

The Integer 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_inline66932 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 Integer (57), new Integer (99));
The reference count of the Association is one, because the variable p refers to it. Similarly, the reference counts of the two Integer instances are one because the Association refers to both of them.

   figure29809
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 Integer 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 Integer objects are now unreferenced and can be garbage collected as well.


next up previous contents index

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