Keeping a list of instances and garbage-collection

grauzone none at example.net
Sun Mar 29 15:00:57 PDT 2009


Jarrett Billingsley wrote:
> On Sun, Mar 29, 2009 at 4:42 PM, Leandro Lucarella <llucax at gmail.com> wrote:
>> This was discussed several times in the past. For example:
>> http://www.digitalmars.com/d/archives/digitalmars/D/learn/weak_references_13301.html
>> http://www.digitalmars.com/d/archives/digitalmars/D/learn/Soft_weak_references_8264.html
>> http://www.digitalmars.com/d/archives/digitalmars/D/announce/ANN_WeakObjectReference_-_class_to_hold_weak_references_9103.html
>> etc.
>>
>> I hope it helps.
> 
> The one provided by Bill:
> 
> http://www.dsource.org/projects/scrapple/browser/trunk/weakref
> 
> seems to work fine, and has the advantage of working in both Phobos and Tango.

First, I doubt this actually works. The WeakRef stores the pointer as 
size_t, but the GC is conservative and will still recognize the size_t 
as a pointer. The unittest in the existing code only works, because he 
uses an explicit delete on the referenced object.

To actually hide the pointer from the GC, you could XOR the size_t value 
with a constant. Note that you need to be very careful with the 
WeakRef.ptr() function: what happens, if the GC invalidates the object, 
and then the user calls ptr() in parallel, before the GC calls 
rt_detachDisposeEvent()? The user will get an invalid pointer. As far as 
I remember, rt_detachDisposeEvent() is supposed to be called when all 
threads have been resumed (after a collect() run). This is to avoid 
deadlocks if the dispose handler locks something.

Secondly, this should be extended by a ReferenceQueue (like in Java). As 
soon as the object referenced by the WeakRef is collected, it is added 
to the ReferenceQueue associated with the WeakRef. (In Java, 
ReferenceQueue.remove() also provides a roundabout way to notify the 
program when a reference has been collected.)

And finally: why is this thing not in Tango?

Maybe a Tango dev could comment on this and the correctness issues 
mentioned above?



More information about the Digitalmars-d mailing list