Search code examples
garbage-collectionocamlinternals

OCaml Product type with independent reachability for each element


According to a section on Rosetta Code (source), OCaml tuples (when returned by functions) are kept alive or collected as a unit.

Space safety of tuples

The OCaml programmer should be aware that when multiple values are returned with a tuple, the finalisation does not handle each values independently, but handles the tuple as a whole. So all the values are only finalised when all the values are not reachable anymore.

I'm wondering whether this is still true in OCaml 4.05 and if there are any alternative ways of getting the same functionality of a product type that doesn't have this property.


Solution

  • I'm not an expert on the OCaml GC, but I would be very surprised if things have changed in this regard.

    One possibility that might have the behavior you want is a weak array, from the Weak module.

    Here's the synopsis for the type 'a Weak.t:

    The type of arrays of weak pointers (weak arrays). A weak pointer is a value that the garbage collector may erase whenever the value is not used any more (through normal pointers) by the program.

    A weak array will have elements of the same type. If you need different types, I guess you could have a tuple of weak arrays each of length 1. The values in the weak arrays would be independently garbage collected. However, the tuple itself would remain until all of the arrays are empty.