Weak Reference Finalizer Guaranteed to Run

Viewed 270

In The cost of weak pointers and finalizers in GHC, Edward Yang writes (emphasis added):

A weak pointer can also optionally be associated with a finalizer, which is run when the object is garbage collected. Haskell finalizers are not guaranteed to run.

I cannot find any documentation that corroborates this claim. The docs in System.Mem.Weak are not explicit about this. What I need to know is, given some primitive that has identity (MutVar#, MutableArray#, Array#, etc.), if I attach a finalizer to it, will it reliably be called when the value gets GCed?

The reason is that I'm considering doing something like this:

data OffHeapTree = OffHeapTree
  { ref :: IORef ()
  , nodeCount :: Int
  , nodeArray :: Ptr Node
  }

data Node = Node
  { childrenArray :: Ptr Node
  , childrenCount :: Int
  , value :: Int
  }

I want to make sure that I free the array (and everything the array points to) when an OffHeapTree goes out of scope. Otherwise, it would leak memory. So, can this be reliably accomplished with mkWeakIORef or not?

1 Answers
Related