[Gc] Question about weak references

Boehm, Hans hans.boehm at hp.com
Tue Dec 5 15:13:18 PST 2006


Not having run the code, it looks OK.  Note that this does not give you
a way to notify any code, and this kind of weak pointer will be cleared
even if it is referenced by objects that are unreachable, but have not
yet been finalized.

In the multithreaded case, you should access the weak pointer while
holding the allocation lock (GC_call_with_alloc_lock()), since the
collector currently clears weak pointers after all mark bits have been
computed and the world has been restarted.  Otherwise you risk turning a
weak pointer into a strong pointer after the collector has already
decided to reclaim the object.

You of course still have to watch all the usual issues with finalization
and weak pointers (cf. my 2005 JavaOne talk,
http://developers.sun.com/learning/javaoneonline/2005/coreplatform/TS-32
81.pdf )

Hans

> -----Original Message-----
> From: gc-bounces at napali.hpl.hp.com 
> [mailto:gc-bounces at napali.hpl.hp.com] On Behalf Of Stephane Epardaud
> Sent: Tuesday, December 05, 2006 12:48 AM
> To: gc at napali.hpl.hp.com
> Subject: [Gc] Question about weak references
> 
> Hi,
> 
> I read that the GC supports weak pointers by using 
> GC_general_register_disappearing_link, is the code below 
> something that makes sense to get weak pointers ?
> 
> struct weak_pointer {
>    void *data;
> };
> 
> struct weak_pointer* make_weak_pointer(void *data){
>    struct weak_pointer* ptr =
>     (struct weak_pointer*)GC_malloc_atomic(sizeof(struct 
> weak_pointer));
>    ptr->data = data;
>    GC_general_register_disappearing_link(&(ptr->data), data);
>    return ptr;
> }
> 
> struct some_struct *s =
>    (struct some_struct*)GC_malloc(sizeof(struct 
> some_struct)); struct weak_pointer * ptr = 
> make_weak_pointer(s); s = NULL; // at this point the GC 
> _could_ collect s and set ptr->data to NULL
> 
> does this look like the way to do it ? (minus some error 
> checking on the way) Thanks.
> _______________________________________________
> Gc mailing list
> Gc at linux.hpl.hp.com
> http://www.hpl.hp.com/hosted/linux/mail-archives/gc/
> 



More information about the Gc mailing list