You can use System.Mem.Weak.addFinalizerfor this.
Unfortunately, the semantics for weak links can be a little difficult to understand at first. A warning note is especially important.
If you can attach IORef, MVaror TVarto your key and make a weak link / finalizer with it, it will probably be much more reliable.
In the special case, when your key is a pointer to unmanaged memory (for example, some C data structure), you must create ForeignPtrand attach a finalizer to it. The semantics for these finalizers are slightly different; rather than an arbitrary I / O action, the finalizer should be a pointer to an external function.
source
share