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]
Peter Smet wrote:
Anyway, when I test the idea, the objects in the WeakKey Dictionary never seem to get garbage collected, even
What am I doing wrong? I am puzzled by the class comment in WeakKeyDictionary which states:
I don't know what's wrong. It should work, but it may take some time, as there would be a garbageCollection for weak values to be released. What WeakKeyDictionary class Comment says about registering its instances, is:
a _ WeakKeyDictionary new. WeakArray addWeakDependent: a. a at: Object new put: 70. Smalltalk garbageCollect. a
print this expression, you should get an empty WeakKeyDictionary. If you comment out the line starting with 'WeakArray', and you print it, you'll get a WeakKeyDictionary with (nil->70). If you register a weak instance, when any of its values is released (becouse it's no longer referenced by anybody), it gets sent #finalizeValues. (Take a look at WeakKeyDictionary | #finalizeValues, WeakArray | #finalizationProcess and WeakArray | #addWeakDependent:)
Referenced Bye! Richie++
squeak-dev@lists.squeakfoundation.org