[Newbies] Re: What is a "weak" reference
nicolas cellier
ncellier at ifrance.com
Tue Jul 15 21:21:17 UTC 2008
Bert Freudenberg a écrit :
>
> Am 15.07.2008 um 13:23 schrieb nicolas cellier:
>
>> Bert Freudenberg a écrit :
>>> The dependents are weak only for "regular" objects. Proper Models
>>> handle their own dependents collection in a non-weak manner.
>>> - Bert -
>>
>> Hmm, not really
>>
>> "Warning: this example is stupid!"
>> | tmp |
>> tmp := Model new.
>> tmp addDependent: #x.
>> tmp addDependent: #y.
>> tmp dependents class. "=> DependentsArray"
>>
>> DependentsArray is a class that holds weakly to its elements...
>>
>> The difference is that the DependentsArray itself don't have to
>> pollute the global WeakIdentityKeyDictionary (Object classPool at:
>> #DependentsFields).
>
> You are right, I was mislead by Object>>dependents ...
>
>> But maybe we have just quit the beginners rails...
>
>
> ... and you are right again.
>
> - Bert -
While we are at it, here is a lesson i learned recently:
| weak obj |
weak := WeakIdentityKeyDictionary new.
"Create an Object"
obj := Object new.
"Add a weak reference to this Object"
weak at: obj put: (Array with: obj).
"This DoIt methods points to the Object via it's temporary variable.
Clear this pointer, so that the Object can eventually be reclaimed"
obj := nil.
"Now garbageCollect to reclaim the weak references"
Smalltalk garbageCollect.
"Let us see if the Object was reclaimed:"
^weak size
Why the object obj was not reclaimed?
Obviously, the WeakKeyAssociation value is not weak...
It is a strong pointer and points strongly to obj through the Array...
Trivial, you might say.
Well yes, it is just http://bugs.squeak.org/view.php?id=7119 in disguise
and i find it nasty.
So be very carfull with Weak references - not only newbs - issues might
definitely be advanced to track down...
Nicolas
More information about the Beginners
mailing list