Native Resource Management

COM uses a reference count to track the life cycle of each COM interface in order to release the resources held by an interface when it is no longer being used. This reference count technique is quite different to the Garbage Collection mechanism implemented by Java. SWTtoCOM hooks in to the Java Garbage Collector in order manage the reference count on COM interfaces. The SWTtoCOM Resource Manager provides this feature.

The SWTtoCOM Resource Manager is responsible for releasing held COM interface references and other automation objects such as pointers. When an automation object is finalised by the Java garbage collector, if it still references a native automation instance the object registers itself with the SWTtoCOM Resource Manager. The finalise method itself cannot be used to release references since it is often run in a background thread and automation instances must be released by the SWT UI thread (See discussion on Threads for more detail on this). The SWTtoCOM Resource Manager registers a SWT timer and so that in some predefined future time it can release the COM interfaces using the SWT UI thread. The SWT timer period is defined to give the finalisation process time to complete so that all automation instances can be released a single pass significantly improving performance.

You can also use the dispose() method of automation object to dispose of the native resources held by that object. By doing so the object will release it resources immediately and will not need to register itself with the SWTtoCOM Resource Manager when it is finalised. You must of course not attempt to use an automation object after having called its dispose() method. If you do the results will be undetermined.

Customising the SWTtoCOM Resource Manager

The SWTtoCOM Resource Manager provides a static method setReleaseInterval to control the interval in which automation objects are released. The release interval is the number of milliseconds between calls for which the manager will release automation object references. A negative or zero value indicates that resources will be released immediately. Be very careful using this since it may cause a significant performance degredation as the finalization process continually calls the SWT UI thread to release the automation object references.

// Set the SWTtoCOM Resource Manager Release Interval to 5 seconds
STCResourceManager.setReleaseInterval(5000); // 5000 milliseconds.