[Gc] Question about gc_cleanup
hans.boehm at hp.com
Wed Nov 2 10:16:20 PST 2005
If you need all files closed at process exit, this is a bit tricky. It
can be done as described in the running example in my JavaOne 2005 talk
(reformatted slides are also at
(This does use some Java idioms, including the ugly one of using
synchronization to keep an object reachable for finalization purposes.
In C++, you'd probably just pass it to a separately-compiled function.
In the g++ dialect of C++, you'd pass it to an empty inline assembly
In general, you should explicitly close files when easily possible.
When not, it's usually relatively easy to use finalization to limit the
number of unreachable open files, at least if your open file limit is
reasonable, and assuming it's OK to have any remaining files closed by
the system at exit. If you run your example in a loop, you should find
that the vast majority of files are closed by the finalizers. (Most
likely, the last two would not be, because they are still referenced
from some machine register where they were temporarily saved. A
nonconservative collector would probably avoid this particular case, but
there are still no guarantees.)
If neither of those are acceptable, you can use a technique such as the
above to explicitly close any files still left open.
In general, finalization is inherently tricky, no matter how you
implement it. You should avoid it if you can.
> -----Original Message-----
> From: gc-bounces at napali.hpl.hp.com
> [mailto:gc-bounces at napali.hpl.hp.com] On Behalf Of Miki Tebeka
> Sent: Wednesday, November 02, 2005 5:14 AM
> To: Ben Hutchings
> Cc: GC mailing list
> Subject: Re: [Gc] Question about gc_cleanup
> Hello Ben,
> > >The problem is that it looks like the finalizers aren't called:
> > You should not rely on finalisers ever being called. See
> Hans Boehm's
> > paper "Destructors, Finalizers, and Synchronization"
> > <https://www.hpl.hp.com/techreports/2002/HPL-2002-335.html>
> for a full
> > explanation of the difference between destructors and finalisers.
> So how can I avoid resource leaks? (Apart from closing files
> Miki Tebeka <mtebeka at qualcomm.com>
> The only difference between children and adults is the price
> of the toys
More information about the Gc