Algorithm for finalizing cycles (Re: [Python-Dev] Garbage collecting closures)

Martin v. L÷wis martin@v.loewis.de
15 Apr 2003 07:13:02 +0200


Greg Ewing <greg@cosc.canterbury.ac.nz> writes:

> What bothers me, though, is that even with finalizers, the library
> writer *still* can't guarantee eventual reclamation.  The application
> can unwittingly stuff it all up by creating cycles, and there's
> nothing the library writer can do about it.

That is not so. If the object having a finalizer doesn't support
references to arbitrary other objects, then the application cannot
make this object be part of a cycle. This is while file objects will
be eventually closed: they cannot be part of a cycle.

Being-referred-to from a cycle is fine: If the cycle itself has no
objects with finalizers, GC will break the cycle at an arbitrary point
and thus release all objects in the cycle, which will then release the
object with a finalizer, which will run the finalizer.

So my usage guideline is this: If you need a finalizer, always make
two objects. One carries the resource being encapsulated, and nothing
else. The other one is the object exposed to applications, which has a
reference to the resource.

Regards,
Martin