Python vs Java garbage collection?

Robert Oschler Oschler at earthlink.net
Mon Dec 23 18:52:04 EST 2002


"Samuele Pedroni" <pedronis at bluewin.ch> wrote in message
news:3e0701a1$1_5 at news.bluewin.ch...
> >
>
> Honestly not closing files explicitly is a bad idea, unless for quick
hacks.
>

Samuele, if you are saying this in the spirit of diminishing the value of
destructors, then read on.  If not, pardon me, I misunderstood.  Sure the
following construct (pseudo-code) handles many situations quite well:

    allocate resource

    try
        # do things
    finally
        # cleanup no matter what

But here's a general description of where automatic resource cleanup via
destructors can be a life saver.  You have an object that has long-term
persistence that allocates an important resource upon its creation.  This
object is passed between several containers that store objects temporarily,
and the object creators that commit the object to the container, are long
gone and therefore any try/finally blocks they might have are irrelevant.
Perhaps the object  is also accessed across several threads and the
container is an application global one, protected by a locking mechanism.
In addition, several other utility classes acquire references to the object
during their lifetime.  In situations like these, having the object
automatically release the resource only when every other reference holder
has "let go" of the object, but immediately at the critical moment, is the
most failsafe and bulletproof approach to managing the resource.  Trying to
ensure the calling of a user-defined "cleanup" call in such a situation is
world-class headache and debugging nightmare.

Situations like the one described above are actually pretty common, an
example of which is when you get into asynchronous event handling which is
fairly germane to any Socket application with persistent objects.  There are
many other examples; sound board accelerator channel acquistion, speech
reco/synthesis instance acquistion, etc. especially in server environments.
In these situations I became a fiend for the C++ Boost shared_ptr library
and it was a lifesave on many an occassion.

thx





More information about the Python-list mailing list