Search This Blog

Monday, January 31, 2005

Self-disposing Resource Pattern

A few mon, I have encountered a quite disturbing problem (see below). Until recently, I found that this problem can be solved by a interesting class, SoftReference, in Java. So, I formulated the following pattern. It's still a rough draft, but I would like to publish it first.

Name: Self-disposing Resource Pattern (Java)
Context: A is some expensive resource that may or may not be pooled. A is used to create another kind of resource, B. If A is disposed, it cannot create B anymore. However, if A is not disposed, the system may run out of memory.
Problem: Determine when to dispose A.
Solution: Java comes with SoftReference class for memory management. “An object is softly reachable if it is not strongly reachable but can be reached by traversing a soft reference.” An A instance can be registered to a resource manager to be a soft reference when it is no longer reachable by any thread. On the other hand, the resource manager can start off a thread to dequeue the SoftReference instances from a reference queue and clean up the resource properly.

No comments:

Popular Posts