Re[2]: [Gc] weak maps and libgc

Ivan Maidanski ivmai at
Mon Oct 31 07:26:13 PST 2011

Hello Andy,

27 10 2011, 12:13 Andy Wingo <wingo at>:
> Hi Ivan,
> On Thu 27 Oct 2011 07:18, Ivan Maidanski <ivmai at> writes:
> > To remove an extra spine segment, I've added a finalizer to the key
> > which unchains the element (spine segment) no longer referring to key
> > (the field is cleared by GC before running finalizers).
> Is there a way to do that if the user wants to add keys to your weak
> table that already have finalizers?  I guess you chain the finalizers,
> then?  OK, thanks; hadn't thought of that.

To say in terms of C code, the client could register finalizer only at object creation and only via mine API, the latter registers mine finalizer which just calls the client one. If, later, the client wants to create some sort of a weak reference which needs an action when the object becomes no longer strong-reachable, then I re-register mine finalizer with a more complex one (this is just an optimization as such case looks to me as rare) passing also some collector-visible data (client_data parameter).
So, I use 2 BDWGC-specific features:
- ability to re-register (and manually unregister) a finalizer;
- ability to pass some client_data pointer (visible to GC).

> >> 6. There is no way around the fact that values in a weak-key map are
> >> strong references, and can thus keep their keys alive
> >> indefinitely.  This issue is covered in the ephemeron paper I
> >> linked to, and could also be solved by the GC.
> >
> > I don't understand what do you mean in 6.
> For a problem description, Java's WeakMap documentation says this:
>   Implementation note: The value objects in a WeakHashMap are held by
>   ordinary strong references. Thus care should be taken to ensure that
>   value objects do not strongly refer to their own keys, either directly
>   or indirectly, since that will prevent the keys from being
>   discarded. Note that a value object may refer indirectly to its key
>   via the WeakHashMap itself; that is, a value object may strongly refer
>   to some other key object whose associated value object, in turn,
>   strongly refers to the key of the first value object. One way to deal
>   with this is to wrap values themselves within WeakReferences before
>   inserting, as in: m.put(key, new WeakReference(value)), and then
>   unwrapping upon each get.

It does not help me understand where is the problem: WeakHashMap is designed to have strong refs for values, it's not a problem.


> For a deeper discussion and a discussion of solutions, see this paper:
> Cheers,
> Andy

More information about the Gc mailing list