Limits on OCaml finalizer execution order across runtime versions
29K reputation · 19 Aug 2023, 15:16 UTC
OCaml’s language manual specifies that finalizers are executed when the garbage collector reclaims a value, but it does not define the order in which multiple finalizers run.
This implementation‑defined behavior can vary between OCaml releases (e.g., 4.12, 4.14, 5.0) and between compilation modes (native code vs. bytecode) or GC settings such as heap size.
Goal: understand whether any ordering guarantees exist for finalizers when objects become unreachable during a single GC cycle, and how runtime configuration influences that order.
Does the OCaml runtime guarantee any relative order of finalizers for objects collected in the same GC safepoint? Does compiling to native code versus bytecode affect the observed sequence? Can altering OCAMLRUNPARAM (e.g., minor heap size) change the finalizer execution order?