wiki

Weak reference

also: ephemeron

A pointer the collector is allowed to ignore when deciding reachability, so a cache can hold a value without keeping it alive. An ephemeron strengthens this to a key/value pair where the value is retained only while the key is independently reachable, which is what makes a memo table not leak.

A weak pointer is one the collector ignores when computing reachability: the value it points at may be collected, and the pointer then reads as empty. It is what lets a cache hold something without deciding its lifetime.

A plain weak table is still wrong for memoisation, because the entry's value usually mentions its key. The table holds the value strongly, the value holds the key, and the key is therefore never collected: the leak survives the weakness. An ephemeron fixes this by making the value reachable only while the key is independently reachable.

OCaml's Ephemeron.K1: `set_key` is weak, and the data is retained only as long as that key is alive elsewhere.

module E = Ephemeron.K1
let memo : (key, value) E.t array = Array.init 256 (fun _ -> E.create ())
let find k =
let slot = memo.(Hashtbl.hash k land 255) in
match E.get_key slot, E.get_data slot with
| Some k', Some v when k' == k -> Some v
| _ -> None

The ordering matters and is the whole reason the primitive exists: a two-field weak record would let the key die while the value lived, or the value keep the key alive, and only the ephemeron rule gives the behaviour a cache actually wants.