[Gc] Re: Do finalizers run at exit?
dej at inode.org
Thu Dec 27 07:28:39 PST 2007
On Thursday 27 December 2007 08:46, Christophe Meessen wrote:
> The possibility to call finalizers is there because of the few
> exceptions where it is required to have them : recycle resources
> controlled by the destructed object like a file descriptor. Keep in mind
> that the program can crash and that the situation where no finalizer is
> called is a possible use case.
And there is the problem: under a tracing garbage collection regime, you have
no control over the lifetime of resources held by an object. If you rely on
finalization to clean up resources, then those resources may be held
indefinitely. Even in Java, with a good generational GC, a long-running
server may have no need to do a full-world collection if the generational
collections are sufficient to provide enough memory to run.
Since you cannot control the lifetime of non-memory resources, GC should not
be used to manage non-memory resources indirectly through finalizers. If you
have objects that manage non-memory resources, then your interactions with
them should be explicit, to bound lifetimes of important resources. For
example, a file reader object with an embedded file handle should have a
close() method which will close the underlying file. In C++ you can have the
destructor for the object call close() automatically, which is a convenience
when the object is created on the stack. However, the destructor won't be
called for an object allocated on a GC heap and therefore if you allocate the
object on the heap you must call close() explicitly.
And if you do that, you have no need for finalizers, period. At least I have
yet to see a good use of finalizers in a well-designed and correct program.
More information about the Gc