[Newbies] What is a "weak" reference

Randal L. Schwartz merlyn at stonehenge.com
Tue Jul 15 15:12:26 UTC 2008

>>>>> "Herbert" == Herbert König <herbertkoenig at gmx.net> writes:

Herbert> Hello cdrick,
c> All that sounds like "don't use weak reference" :)

Herbert> .... unless you know exactly what you are doing.

One possible use I haven't seen in this thread is to "keep notes" on a class
you don't own (and don't want to change), without preventing them from being
GC'ed normally.

For example, if I wanted to write a system watcher that noticed the comings
and goings of Process objects, I'd likely keep a Dictionary keyed by the
Process instance referencing the data of start times.  However, I wouldn't
want that key to keep the Process instance from being gc'ed, so I'd use a weak
dictionary.  This is how the classic "dependents" system works as well: the
dependencies are in a WeakDictionary so that when the watched object goes
away, the dependencies are also cleaned.

The alternative is to add a set of properties to the Process that others can
stuff information, so that "Process allInstances" can get my process watcher
what it needs instead.

Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn at stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.vox.com/ for Smalltalk and Seaside discussion

More information about the Beginners mailing list