[Mono-list] Finalizer never called
Jonathan Pryor
jonpryor@vt.edu
01 Aug 2003 07:58:53 -0400
<snip/>
> A question: could really happen that a finalizer is never called?
> If so, how would managed resources be released?
Is it possible for finalizers to never be called? Yes. Why? Because
of this:
class BadClass {
~BadClass () {
System.GC.ReRegisterForFinalize (this);
}
}
This class will never finalize, because every time the GC attempts to
finalize the class, it requests that it be kept alive.
The basic idea is that the GC keeps track of how many objects need to be
finalized. During process shutdown, as long as this number is
declining, finalizers will continue to be run. If this number stops
declining before reaching 0 (which would occur with the class above),
finalizers stop being executed, just so that the process can be shut
down within a reasonable timeframe.
Additionally, finalizers are run on a different thread, so that if a
finalizer never terminates (e.g. "while (true) {}"), the finalizer
thread can be terminated, allowing the process to shut down in an
orderly fashion.
It's unlikely that either of these situations will occur, but they need
to be taken into consideration. Most of the time, finalizers should
always be run. I would consider failure to do so to be a bug in the
runtime.
- Jon