[Haskell-cafe] Bulletproof resource management

Florian Weimer fw at deneb.enyo.de
Fri Oct 8 12:39:26 EDT 2010

At least in my experience, in order to get proper resource management
for things like file or database handles, you need both a close
operation and a finalizer registered with the garbage collector.  The
former is needed so that you can create resources faster than the
garbage collector freeing them.  The latter is a safety net in cases
where proper resource management is not follwoed (perhaps in GHCi).
When the explicit close operation or the finalizer has been invoked,
the object must somehow be disabled, so that further operations on it
fail (otherwise, you might dereference a dangling pointer).

What's the idom for implementing this in Haskell (or GHC)?  It seems
that a ForeignPtr cannot be written to (otherwise I'd change it to a
null pointer when the resource is freed).  It's also not possible to
check if the finalizers have been run.

Can the finalizers hold a reference to the object which in turn holds
the ForeignPtr to be finalized?  Or would that prevent the finalizers
from running at all?  Is there a way to avoid the extra level of
indirection (or is GHC sufficiently smart to optimize it away)?

More information about the Haskell-Cafe mailing list