WeakKeyDictionary - does this code look right??

Peter Smet peter.smet at flinders.edu.au
Wed Mar 3 11:12:42 UTC 1999


I am trying to do a (very rough) version of event triggering
using a PostOffice class via which all events are relayed.

Objects register an interest in an event by sending the
following message to the PostOffice:

when: anEvent do: aOneArgBlock for: anObject 

The PostOffice should hold onto the all the objects it
needs to notify weakly, so that these can be garbage
collected. I am using a WeakKeyDictionary, in which
the keys are the objects wanting to be notified, and the
values are action blocks. I realise the blocks idea is
a problem, since blocks may have strong references
to objects, but this is an issue for later...

Anyway, when I test the idea, the objects in the WeakKey
Dictionary never seem to get garbage collected, even
if there are no references to them (from the blocks, inspectors
etc.) The WeakKeyDictionary is held by the Singleton instance
of PostOffice. This is despite waiting, shutting down and starting the
image etc.

What am I doing wrong? I am puzzled by the class comment in 
WeakKeyDictionary which states:

"Clients are responsible to register my instances by WeakArray
 such that the appropriate actions can be taken upon loss of any keys."

Does this mean each WeakKeyDictionary must be contained within
a WeakArray?? I would appreciate an example of how this should be done.

Here are the relevant messages from the PostOffice class:

initialize
 events _ Dictionary new.
 self events at: #allEvents put: WeakKeyDictionary new

when: anEvent do: aOneArgBlock for: anObject 
 (self events includesKey: anEvent)
  ifFalse: [self events at: anEvent put: WeakKeyDictionary new].
 (self events at: anEvent)
  at: anObject put: aOneArgBlock

incoming: aMessage 
 (self events at: #allEvents)
  do: [:block | block value: aMessage].
 (self events includesKey: aMessage selector)
  ifFalse: [^ self].
 (self events at: aMessage selector)
  do: [:block | block value: aMessage]





More information about the Squeak-dev mailing list