Join GitHub today
Finaliser that are really called when a value will be freed. #7210
Original bug ID: 7210
Since the values finalized are given as argument of their finalizers, they are kept alive. So you can't be sure that nobody will ever use this value again.
Before 4.03 the finalizer where called after cleaning weak pointers, thus possibly breaking invariant of weakset, hashconsing. In 4.03 they are called before cleaning weak pointers (which is done when we are sure to sweep the value).
It could be interesting to give the possibility to register finalizers that would not take the value as argument but instead
The question is not really how to add this feature (straightforward), more if ocaml needs it.
Comment author: @alainfrisch
Just to be sure to understand the (potential) problem: a finalizer could create a reference to the value being finalized (e.g. by storing it in a global table). If a single finalizer is attached to a value, it would be responsible for this situation, and if it does create a reference to the value, well, it knows that the value won't be collected. I don't think we need to protect against that. A more tricky case is when multiple finalizers are attached to the same value (or to nested values), in which case it's much harder to attach the "responsibility" to any piece of code. Is that the situation you have in mind?
Comment author: @lpw25
This would be very useful in combination with weak pointers.
As of 4.03, it is difficult to "clean up" a data structure containing a weak pointer when the weak pointer is cleared (e.g. removing an entry from a weak hash table once its weak pointer is empty). Previously this could be done with ordinary finalisers, but that is no longer possible since finalisers are now run before weak pointers are cleared.
Ordinary finalisers are now run before clearing weak pointers to make sure that weak pointers are only cleared once the object is genuinely dead -- a useful invariant for things like hash-consing. Since the proposed alternative finalisers do not receive their argument and cannot bring it back to life, they can safely be run after weak pointers have been cleared without breaking the desired invariant on weak pointers.