[MLton-user] Weak pointer regression test 2

Matthew Fluet matthew.fluet at gmail.com
Thu Apr 14 11:12:51 PDT 2011


On Thu, Apr 14, 2011 at 10:03 AM, Ivan Tomac <ivan.tomac at gmail.com> wrote:
> Why does the following code (taken from regression/weak.2.sml) return true,
> and more importantly why is it supposed to return true (according to the
> expected test result in weak.2.ok):
>
> structure Weak = MLton.Weak
>
> val x = (13, ref 5)
> val wx = Weak.new x
> fun isAlive () = isSome (Weak.get wx)
> val _ = MLton.GC.collect ()
> val _ = print (Bool.toString (isAlive ()) ^ "\n")
>
> Shouldn't x be garbage collected?

In this program, the object bound to x can be made global (with only
constant space overhead), and hence it is reachable throughout the
lifetime of the whole program.  This is a space/time tradeoff ---
making such small objects global may waste a little space (because
they are not garbage collected), but can be efficiently accessed
through their global name (rather than threading their pointers
through the program in variables and closures).

Two slight variations on the program will prevent x from being
globalized and lead to the object being garbage collected.

One: make the object bound to x a "large" (technically, not manifestly
small) object:

val x = (13, ref (List.tabulate (100, fn i => i)))
val wx = Weak.new x
fun isAlive () = isSome (Weak.get wx)
val _ = MLton.GC.collect ()
val _ = print (Bool.toString (isAlive ()) ^ "\n")

Two: bind a (mutable) object to x more than once:

fun f _ = let
val x = (13, ref 5)
val wx = Weak.new x
fun isAlive () = isSome (Weak.get wx)
val _ = MLton.GC.collect ()
val _ = print (Bool.toString (isAlive ()) ^ "\n")
in () end
val _ = List.app f (List.tabulate (10, fn i => i))

Both of these programs will print "false".

> I'm having a play with multiMLton branch of MLton and this test fails there
> as it returns false, but that makes more sense as x doesn't seem to be
> reachable from anything.

No idea; you'd have to ask those developers why it uses a different
globalization condition.



More information about the MLton-user mailing list