weak references

PJP pete.poulos at gmail.com
Wed Aug 6 15:49:04 PDT 2008


> Stupid question:  Why would you want weak references other than for circular
> reference elimination with a reference counting GC?

Here are three examples where weak references may or may not be useful:

1) Suppose your application uses a set of large resources (Graphics resources, for instance) and you want to implement a cache for these values such that any request for the same resource returns a shared instance to that resource (to keep the memory footprint down).  However, when the resource is no longer in use, you would like it to be garbage collected.  If your cache maintains a reference to the resource, which it must, then it will prevent that resource from being reclaimed which results in a memory leak.

With weak references, you have the cache maintain weak references to the resources and if the cache is the only thing with a refence to the resource it can be reclaimed by the garbage collector.

You can solve this problem without weak references, in a variety of ways (reference counting or using a fixed cache size and a cache miss algorithm like LRU), and in some cases they may be better solutions for performance reasons.  However, they also require more overhead and and are more error prone (especially if they require the user to release the references to the cache when they are done with them).

2) Suppose you have a class, Window, which provides the operation "minimizeAllWindows."  To implement this, your class needs to maintain a set of all instances of itself.  However, doing so would prevent each of those items from being garbage collected.  With weak set (built using weak references) this set wouldn't prevent the individual instances from being garbage collected.

3) Suppose you have an object, NewsBroadcast, which delivers news to all subscribers.  The NewsBroadcast object must maintain a reference to all subscribers which will in turn hold all of those subscribers in memory.  However, suppose that your subscriber would like to be reclaimed when nothing but the NewsBroadcast holds a reference to it.  

The only way to do this without weak references is to implement a form of reference counting on the subscriber so that you know when NewsBroadcast is the only object with a reference to the subscriber.  When this condition occurs you then unsubscribe from the NewsBroadcast and the object can be reclaimed.  However, this solution is inelegant and very error prone.

PJP



More information about the Digitalmars-d-learn mailing list