[MLton] MLton.GC.collect hangs when using MLton.Finalizable

Matthew Fluet fluet at tti-c.org
Sat Feb 17 06:18:08 PST 2007

Wesley W.Terpstra wrote:
> Compile the attached program and watch it hang in MLton.GC.collect. I am 
> assuming  this is a bug?
> I'm tracing this myself, but am far from an expert on how these parts 
> interact.

I don't see the program diverge, though I do see it raise the Overflow 

The "bug" is in your usage of Finalizable; note that the documentation 
at http://www.mlton.org/MLtonFinalizable states:

   A finalizable value is a container to which finalizers can be
   attached. A container holds a value, which is reachable as long as the
   container itself is reachable. A finalizer is a function that runs at
   some point after garbage collection determines that the container to
   which it is attached has become unreachable.

So, in your code, when you do:

   val b = MLton.Finalizable.new (Ring.add (2, a))
   val () = MLton.Finalizable.addFinalizer (b, remove)

Ring.add (2, a) returns a new link in the ring (call that value b'), and 
then you create the container b (holding b'), to which you add a 
finalizer that removes b'.  But, you immediately drop all references to 
the *container* b, so at any time, the finalizer could run, and remove 
b' from the ring.

In particular, the finalizer could run *during* the loop in fold; where 
it removes the end-of-ring reference, leaving fold to run in an an 
infinite loop.

More information about the MLton mailing list