Microsoft SDK for Java

Reference Counting

Reference counting is handled automatically in Java. As a result, you can create object references without calling IUnknown::AddRef. In addition, calling IUnknown::Release isn’t required when you're finished using a reference to an object. The Java garbage collector automatically keeps track of how many references there are to an object. In practice, however, you may need to ensure a timely release of shared resources. You can use the com.ms.com.ComLib.release method to force Java to release all of its reference counts on a COM object.

In C++, you release a COM object using the following syntax:

pDrawable->Release();

In Java, the equivalent code looks like this:

import com.ms.com.*;
ComLib.release(drawable);

Calling the release method causes the drawable object to release all of its references to the COM object that it wraps. Because drawable may have cached one or more of the object's interfaces, this call may result in more than one release.

Note   If you do not call the com.ms.com.ComLib.release method, normal garbage collection will attempt to perform the release for you. This mechanism is not guaranteed, however, due to the threading limitations of many COM objects. That is, many COM objects can only be called on the thread that they were created on. Because garbage collection occurs at unpredictable times, the required thread may have expired or may no longer be responding to messages by the time garbage collection reclaims the object. In addition, this unpredictability can obscure true memory leaks, tie up important system resources, or both. As a result, use explicit releases to free COM objects quickly and predictably.

© 1999 Microsoft Corporation. All rights reserved. Terms of use.