[Gc] weak maps and libgc

Andy Wingo wingo at pobox.com
Fri Feb 24 09:24:17 PST 2012


On Fri 24 Feb 2012 17:25, Ivan Maidanski <ivmai at mail.ru> writes:

>> Does anyone have ideas about how you could make a weak map whose entries
>> are present until the object is actually collected?
> My idea is to use hidden pointer to object as hash map key and register
> finalizer (probably chaining with the client finalizer) for object which
> deletes the entry in the map.

This works if you are looking up entries by the identity of the key --
if the key becomes finalizable, after there are no guardian finalizers
at the head of the finalizer chain, then that entry can never be found.

However, if you can access entries by some aspect of the key, that
doesn't work.

Let me give an example.  Guile has a "symbol" data type: basically an
interned string.  If two symbols have the same characters, they should
be eq?.

For various reasons, Guile can garbage-collect symbols.  So consider:

  1. You read the expression (lambda () (define (foo) bar) (foo)).

  2. You compile it.  There is no `foo' symbol in the compiled
     procedure.  `foo' is logically collectable now.

  3. The GC decides `foo' is collectable and queues a finalizer to
     remove it from the symbol table.

  4. You read another expression: (lambda () (define (foo) bar) (foo)).

  5. In between reading the first `foo' and the second `foo', the
     finalizer runs.

  6. Now you have two `foo' symbols, with the same characters but
     different identities.  Oops!

This problem doesn't occur with disappearing links, because they are
synchronized with the collector.  Finalizers are not synchronized, so
they can race with the mutator.

> PS. I wonder whether it's possible in Java? (PhantomReference keeps the
> reference to object while it is alive but you can't get that reference.)

I don't know :)  After having spent an hour or so now looking at this,
I'm not clear on what you would do here.  PhantomReference + reference
queues seems to be like guardians, but you can't resuscitate the object.
It seems to me that the entries in an associated weak map would remove
themselves either too early (via a dropped weakref) or too late (via an
asynchronous poll on the refqueue).

Food for thought!


More information about the Gc mailing list