Monday, June 16, 2008

Resource Collector Pattern

There are scenarios in which the ownership of Disposable or Both objects is not well defined. For example, the reference to an object may be handed off to multiple clients. In such scenarios, it is very difficult, if not impossible, to dispose the scarce resource as soon as it is no longer needed. None of the clients knows when the other clients are done with the object.
One set of solutions to the problem relies on letting the finalizer collect the resources and just forcing the GC to collect more often than it normally would. We call such solutions Resource Collectors. Resource Collectors helps to minimize the time between when the resource is available for collection and the time when the finalizer actually runs and releases the resource. One drawback of such an approach is that forcing collection, if abused, may actually lead to performance loss. Good implementations of the pattern employ clever algorithms determining when forced collection should be executed.
One such implementation, a component called HandleCollector, can be downloaded from the GotDotNet site (http://GotDotNet). The collector maintains a counter of “live” resources. The counter is incremented when a resource is allocated and is decreased when the resource is released by the finalizer. When a new resource is about to be allocated and the counter is greater than an application specified threshold, collection is forced by a call to GC.Collect.
A degenerated version of a Resource Collector implementation uses a timer to force collection at specified intervals. Such an implementation is discouraged. The implementation described above is much better at forcing collection when needed and avoiding unnecessary collections which may significantly impair performance and scalability.

No comments: