Python vs Java garbage collection?

"Martin v. Löwis" martin at v.loewis.de
Mon Dec 23 17:44:00 EST 2002


Robert Oschler wrote:
> I'd like there to be a method of an object that is called the instant an
> object's reference count drops to 0 and not when the garbage collector gets
> around to cleaning up.  

I see. This is precisely the definition of Python's __del__ method: it 
is called when the reference count drops to zero, atleast for CPython.

Now, for some objects, the reference count never drops to zero, because 
they are part of cycles (or reachable from cycles); given your 
specification, I assume you would expect that destructor is never called 
for these objects.

Python goes beyond that (atleast from 2.0 on): the cyclic garbage 
collector finds breaks (some) cycles; objects with finalizers that are 
reachable from cycles (but are not part of the cycle) have their __del__ 
invoked when the cycle is broken. This is actually more than you've 
asked for, since you expected that those objects never have their 
finalizers called.

If objects with finalizers are part of the cycle, it is not clear how to 
  break it (since the finalizer may bring the object back to live, but 
some references are already broken); those objects are put into 
gc.garbage instead.

> The implied assumption is also that all object reference
> counts drop to 0 on program termination, if not, then that additional
> behavior too, so that program global objects could be counted on to have
> their destructors called at some time.

This is not the case in Python; objects with finalizers never have their 
finalizers called because of the resulting semantic difficulties. It 
should be considered a bug in an application if it has such objects when 
the application terminates.

> If garbage collected languages would have trouble adopting this behavior,
> due to the treachery of releasing an object's memory outside of the garbage
> collector's normal "schedule"

Languages with garbage collection have a problem with this strategy if 
they don't maintain a reference counter - then there is no efficient way 
to find out whether it has dropped to zero. Java is one such language, 
that's why it cannot guarantee timely invocation of the finalizer.

Regards,
Martin




More information about the Python-list mailing list