[Newbies] What is a "weak" reference

Bert Freudenberg bert at freudenbergs.de
Tue Jul 15 05:43:30 UTC 2008

Am 14.07.2008 um 09:51 schrieb Rob Rothwell:

> On Mon, Jul 14, 2008 at 11:42 AM, Todd Blanchard  
> <tblanchard at mac.com> wrote:
> So how do you make a weak reference? You stick a WeakArray in as a  
> holder.  So in your parent/child objects you would write something  
> like:
> Node>>parent
>        ^ parent ifNotNil: [parent first] ifNil: [parent]
> Node>>parent: p
>        parent := p ifNotNil: [WeakArray with: p] ifNil: [p]
> thus using a WeakArray as a holder for the parent.
> When a weak reference gets garbage collected, its weak references  
> are set to nil first.
> Thank you!  This is what I wanted to know; I'll give this a try, and  
> see how it works for me...
> So many Classes, so little time...

Well, Todd certainly knows when he needs to introduce weak refs but a  
simple parent-child relation (say, in a tree) is *not* a good example  
for this. The parent reference in a child does not prevent it from  
being garbage-collected, unless there exist other references to it.  
You cut the child link and it's gone. But if there are indeed other  
references to the child weak refs would just mask the problem because  
the parent may get garbage-collected but the child is not. The problem  
in that case typically is not the parent/child links but those other  

In a clean design you very rarely need weak refs. Also, you need to  
sprinkle your code with ifNil: tests because a weak ref can become nil  
any time.

- Bert  -

More information about the Beginners mailing list