[Gc] Re: Do finalizers run at exit?

Shiro Kawai shiro at lava.net
Sat Dec 29 14:50:13 PST 2007

From: Achilleas Margaritis <axilmar at otenet.gr>
Subject: [Gc] Re: Do finalizers run at exit?
Date: Sat, 29 Dec 2007 22:58:50 +0200

> Thanks a lot for replying, but my question is still unanswered.
> It's not a difficult question, is it? I am just asking why finalizers are
> NOT invoked AT EXIT, while they are INVOKED after a COLLECTION.

- Finalizers may not be able to invoked IMMEDIATELY after a collection,
  in fact, their invocation can be DELAYED INDEFINITELY.

- You can not delay program termination INDEFINITELY, in general.

- If you know your application uses finalizers in a way that it is
  guaranteed to be called in reasonalbe, bounded time (which GC
  can't know in general---only you know), there's a back door I've
  shown.  However, for the usage of system resource release or
  temporary file removal, there's a better way not to directly
  rely on finalizers to do, so it is debatable WHY you want the
  finalizers to run on exit.

> At exit, there is no need to revive objects, as the application is
> exiting. You just call the finalizers of all remaining objects.
> If a destructor happens to allocate memory (highly impropable,
> but possible), then the collector might delay exiting a little until
> the newly allocated memory is no longer used. It's acceptable, as it
> is a design flaw to do such an action anyway in a finalizer.

The point is that GC doesn't know what finalizers do, and it is
so easy to mess things up with finalizers.

What I do in my app is to use finalizers for the last resort of safety
net (my app is a language implementation, so I can't be sure if
the programmers of the language always release resources properly).
But for the resource release at exit, I do it explicitly in my
own exit handler, keeping weak references to the active objects
that grab resource handles.  
(BTW, that is what the mentioned paper suggests---I downloaded
it and realized I've read it before.  It uses temporary file
removal as an example, which may be relevant to your app.)

This may be a debate about where the line should be drawn between
GC library and application.   Rich GC library could support such a
cleanup-upon-exit utility.  IMHO, it is a layer _above_ the GC,
and I expect the GC library to do a right thing with enough hooks
so that I can roll my own cleanup stuff on top of it.


More information about the Gc mailing list