MLton / mlton

The MLton repository

Home Page:http://mlton.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Function to run finalizers

pclayton opened this issue · comments

This issue continues from the thread 'Running finalizers on exit' on the MLton-user list.

In summary, it was observered that exiting using Posix.Process.exit does not run finalizers so a function to explicitly run finalizers would be useful. A function

val gcAndFinalize : unit -> unit

was proposed that garbage collects and finalizes as much as possible. I now think that fullGCAndFinalize would be a slightly better name as some compilers may offer different levels of GC.

Since then, I have wondered whether it could be useful to provide a more general finalization function

val finalize : (unit -> unit) -> bool

which

  1. allows the caller to specify the GC function as the argument, and
  2. evaluates the GC function once and then runs finalizers synchronously, returning a flag indicating whether any finalizers were run (so false means there are no more finalizers that can be run).

The synchronous nature gives more predictable timing and the choice of GC function and return flag allow the caller to trade-off time versus completeness. This would give some control over scheduling of GC and finalization to an application, potentially reducing the likelihood of a user experiencing pauses.

Also, this should allow fullGCAndFinalize to be implemented as

while finalize MLton.GC.collect do ()

Closing to start a discussion instead.