[Gc] Re: Do finalizers run at exit?
axilmar at otenet.gr
Fri Dec 28 08:08:29 PST 2007
O/H David Jones έγραψε:
> 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.
That's why you can invoke a manual collection when required.
> Since you cannot control the lifetime of non-memory resources, GC should not
> be used to manage non-memory resources indirectly through finalizers.
Oh no, this is a solution of type 'head hurts, we cut head'. Not all
shoes are appropriate for the same foot.
> 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.
Then can I assume you have never made a program in which a resource must
be shared between its heap-allocated objects!!! :-)
More information about the Gc