Reference Counting

Even if you expect your code to be run only on the most modern, high-powered computer systems, you should try to keep unnecessary pieces of code from cluttering up main memory. COM employs a system of reference counting to determine whether a COM component should remain resident in memory. IUnknown implements two functions that manage reference counts: AddRef and Release. In general, whenever a pointer to an interface is provided, AddRef should be called to increment a reference counter; when that interface pointer is no longer needed or in use, Release should be called to decrement the counter. When the reference counter reaches 0, the COM component can remove itself from memory. In some cases, the reference count will refer to the sum total of all pointers—whatever their interface type—that refer to a given COM object; in other cases, individual interfaces will track individual reference counts. The latter approach will be used, for example, when different interfaces implement discrete pieces of code. The Release method will usually remove a COM object from memory when all reference counts reach 0.

In Java, reference counting is handled internally by the virtual machine; the built-in IUnknown interface implements general versions of AddRef and Release that are automatically called by your Java code. The JVM manages COM objects in much the same way that it handles regular Java objects, performing automatic garbage collection when an object is no longer referenced by an application.

© 1997 by Scott Ladd. All rights reserved.