Garbage collection

Duncan Booth duncan.booth at invalid.invalid
Tue Feb 19 11:18:24 CET 2008


Jarek Zgoda <jzgoda at o2.usun.pl> wrote:

> Duncan Booth napisa³(a):
> 
>> Pretty much. If you have a __del__ method on an object then in the
>> worst case the only thing that can be guaranteed is that it will be
>> called zero, one or more than one times. (Admittedly the last of
>> these only happens if you work at it).
>> 
>> If it is called then is may be either immediately the last reference
>> to the object is lost, or it may be later when the garbage collector
>> runs (and not necessarily the first next time the garbage collector
>> runs). 
> 
> Java finalizers are not called upon VM exit, only when object is swept
> by GC (for example when the object is destroyed upon program exit),
> the CPython docs read that this is the case for Python too. Is this
> behaviour standard for all VM implementations or is
> implementation-dependent (CPython, Jython, IronPython)?
> 
Yes, CPython does reference counting so it can call __del__ immediately 
an object is unreferenced. The GC only comes into play when there is a 
reference loop involved. If an object is directly involved in a 
reference loop then __del__ is not called for that object, but a loop 
could reference another object and its __del__ would be called when the 
loop was collected.

Other Python implementations may behave differently: presumably Jython 
works as for Java (but I don't know the details of that), and IronPython 
uses the CLR which has its own peculiarities: finalizers are all called 
on a single thread which is *not* the thread used to construct the 
object, so if you use finalizers in a CLR program your program is 
necessarily multi-threaded with all that implies. Also it takes at least 
two GC cycles to actually release memory on a CLR object with a 
finalizer, on the first cycle objects subject to finalization are simply 
added to a list (so are again referenceable), on the second cycle if the 
finalizer has completed and the object is unreferenced it can be 
collected. CLR finalizers also have the interesting quirk that before 
the finalizer is called any references the object has to other objects 
are cleared: that allows the system to call finalizers in any order.

Otherwise I think the behaviour on exit is pretty standard. If I 
remember correctly there is a final garbage collection to give 
finalizers a chance to run. Any objects which become newly unreferenced 
as a result of that garbage collection will have __del__ called as 
usual, but any which merely become unreachable and therefore would be 
caught in a subsequent garbage collection won't.



More information about the Python-list mailing list