Previous: , Up: Miscellaneous Datatypes   [Contents][Index]


10.7 Weak References

Weak references are a mechanism for building data structures that point at objects without protecting them from garbage collection. An example of such a data structure might be an entry in a lookup table that should be removed if the rest of the program does not reference its key. Such an entry must still point at its key to carry out comparisons, but should not in itself prevent its key from being garbage collected.

A weak reference is a reference that points at an object without preventing it from being garbage collected. The term strong reference is used to distinguish normal references from weak ones. If there is no path of strong references to some object, the garbage collector will reclaim that object and mark any weak references to it to indicate that it has been reclaimed.

If there is a path of strong references from an object A to an object B, A is said to hold B strongly. If there is a path of references from an object A to an object B, but every such path traverses at least one weak reference, A is said to hold B weakly.

MIT Scheme provides two mechanisms for using weak references. Weak pairs are like normal pairs, except that their car slot is a weak reference (but the cdr is still strong). The heavier-weight ephemerons additionally arrange that the ephemeron does not count as holding the object in its key field strongly even if the object in its datum field does.

Warning: Working with weak references is subtle and requires careful analysis; most programs should avoid working with them directly. The most common use cases for weak references ought to be served by hash tables (see Hash Tables), which can employ various flavors of weak entry types, 1d tables (see 1D Tables), which hold their keys weakly, and the association table (see The Association Table), which also holds its keys weakly.


Previous: Streams, Up: Miscellaneous Datatypes   [Contents][Index]