[Gc] Re: Do finalizers run at exit?

Andrew Haley aph at redhat.com
Thu Dec 27 10:27:18 PST 2007

Christophe Meessen writes:

 > The problem boils down to resource leaks caused by exceptions. A GC
 > gracefully crush this problem to oblivion. It solves the memory
 > leak problem and, by use of finalizers, any other type of resource
 > leaks.
 > Considering your close() method example, a user would have to add
 > try catch blocks in many places of its code to ensure the object is
 > properly closed if something goes wrong. Adding a finalizer calling
 > the close() method avoids this.

In practice we've discovered that GC finalizers are not sufficient for
extremely scarce resources such as file descriptors because you aren't
guaranteed that collection will happen in time.  Of course you can
trigger manual collections to encourage the GC to Do The Right Thing,
but it's better explicitly to close() as soon as you're done, and use
catch blocks to make sure that happens.

 > Note well that the sole role of this finalizer is to be a kind of
 > safety net to recycle lost resources occurring in exceptional
 > circumstances. As you wrote, a user should be required to use the
 > close() method so that resource lifetime is properly controlled in
 > normal circumstances.

Well, OK, but a program that leaks file handles in exceptional
circumstances has a bug.  Sure, it's worth adding a finalizer just in
case, but it's not right to rely on it.


Red Hat UK Ltd, Amberley Place, 107-111 Peascod Street, Windsor, Berkshire, SL4 1TE, UK
Registered in England and Wales No. 3798903

More information about the Gc mailing list