Module Weak_hashtbl
A hashtable that keeps a weak pointer to each key's data and uses a finalizer to detect when the data is no longer referenced (by any non-weak pointers).
Once a key's data is finalized, the table will effectively behave as if the key is not in the table, e.g., find
will return None
. However, one must call reclaim_space_for_keys_with_unused_data
to actually reclaim the space used by the table for such keys.
Unlike (OCaml's) Weak.Make
, which also describes itself as a "weak hashtable," Weak_hashtbl
gives a dictionary-style structure. In fact, OCaml's Weak.Make
may better be described as a weak set.
There's a tricky type of bug one can write with this module, e.g.:
type t =
{ foo : string
; bar : float Incr.t
}
let tbl = Weak_hashtbl.create ()
let x1 =
let t = Weak_hashtbl.find_or_add tbl key ~default:(fun () ->
(... some function that computes a t...))
in
t.bar
At this point, the data associated with key
is unreachable (since all we did with it was project out field bar
), so it may disappear from the table at any time.