Chapter 13

Memory Management

13.1  Weak Boxes

A weak box is similar to a normal box (see section 3.9), but when the automatic memory manager can prove that the content value of a weak box is only reachable via weak boxes, the content of the weak box is replaced with #f.

13.2  Will Executors

A will executor manages a collection of values and associated will procedures. The will procedure for each value is ready to be executed when the value has been proven (by the automatic memory manager) to be unreachable, except through will executors, weak boxes, weak hash table keys, and custodians. A will is useful for trggering clean-up actions on data associated with an unreachable value, such as closing a port embedded in an object when the object is no longer used.

Calling the will-execute or will-try-execute procedure executes a will that is ready in the specified will executor. Wills are not executed automatically, because certain programs need control to avoid race conditions. However, a program can create thread whose sole job is to execute wills for a particular executor.

If a value is registered with multiple wills (in one or multiple executors), the wills are readied in the reverse order of registration. Since readying a will procedure makes the value reachable again, the will must be executed and the value must be proven unreachable once again before another of the wills is readied or executed. However, wills for distinct unreachable values are readied at the same time, regardless of whether the values are reachable from each other.

If the content value of a weak box (and/or a key in a weak hash table) is registered with a will executor, the weak box's content is not changed to #f (and/or the weak hash table entry is not removed) until all wills have been executed for the value and the value has been proven unreachable again.

13.3  Garbage Collection

(collect-garbage) forces an immediate garbage collection. Since MzScheme uses a ``conservative'' garbage collector, some effectively unreachable data may remain uncollected (because the collector cannot prove that it is unreachable). This procedure provides some control over the timing of collections, but garbage will obviously be collected even if this procedure is never called.

(current-memory-use [custodian]) returns an estimate of the number of bytes of memory occupied by reachable data from custodian. (The estimate is calculated without performing an immediate garbage collection; performing a collection generally decreases the number returned by current-memory-use.) If cuostdian is not provided, the estimate is a total reachable from any custodians. Unless MzScheme is compiled with special support for memory accounting, the estimate is the same (i.e., all memory) for any individual custodian.

(dump-memory-stats) dumps information about memory usage to the (low-level) standard output port.