[MLton] adding synchronous finalizers

Stephen Weeks MLton@mlton.org
Fri, 1 Oct 2004 15:12:52 -0700

> Probably just being silly, but your code creates new thunks and list
> pairs every time the list of finalizers is run.

To be clear, it only allocates once per finalizable object -- when
that object is moved from the list of "possible finalizers" stored by
MLton.Finalizable to the list of "definite finalizers" stored in my

> I agree that from a semantics point of view, it makes sense to check
> the value stored in synchronously ever time an individual finalizer
> is called, but I would probably add an optimization to check it in
> runFinalizers as well.  I.e., if synchronously is true, then
> runFinalizers can just return the empty list, right?

I think you're confused.  If synchronously is true, then runFinalizers
is supposed to run all the finalizers that have been added to the
finalizers list.  If synchronously is false, then runFinalizers will
do nothing because the list will be empty.

> I would argue strongly that running finalizers when I call
> setRunSynchronously with a true arg is bad.

Confusion?  My code runs finalizers for setSynchronously false,
i.e. when switching from synchronous mode to asynchronous mode.  The
idea is that in synchronous mode, finalizers may accumulate, and when
we switch to asynchronous mode we need to make sure that the
accumulated finalizers run sometime.  I chose to run them immediately.
Another option would be to put them someplace so they happen at the
next GC with other finalizers, but that requires getting inside the
MLton.Finalizable implementation (not necessarily a bad idea).
Another option would be to report an error if there are any
accumulated finalizers.