Previous Section | Next Section | Table of Contents | Glossary | Index |
In general, a "weak reference" is a reference to an object which does not prevent the object from being garbage-collected. For example, suppose that you want to keep a list of all the objects of a certain type. If you don't take special steps, the fact that you have a list of them will mean that the objects are always "live", because you can always reference them through the list. Therefore, they will never be garbage-collected, and their memory will never be reclaimed, even if they are referenced nowhere else in the program. If you don't want this behavior, you need weak references.
CCL
supports weak references with two kinds of objects:
weak hash tables and populations.
Weak hash tables are created with the standard Common Lisp
function make-hash-table
, which is extended
to accept the keyword argument :weak
. Hash
tables may be weak with respect to either their keys or their
values. To make a hash table with weak keys, invoke
make-hash-table
with the option :weak t, or,
equivalently, :weak :key. To make one with weak values, use
:weak :value. When the key is weak, the equality test must be
#'eq (because it wouldn't make sense otherwise).
When garbage-collection occurs, key-value pairs are removed from the hash table if there are no non-weak references to the weak element of the pair (key or value).
In general, weak-key hash tables are useful when you want to use the hash to store some extra information about the objects you look up in it, while weak-value hash tables are useful when you want to use the hash as an index for looking up objects.
A population encapsulates an object, causing certain
reference from the object to be considered weak. CCL
supports
two kinds of populations: lists, in which case the encapsulated
object is a list of elements, which are spliced out of the list
when there are no non-weak references to the element; and alists,
in which case the encapsulated object is a list of conses which
are spliced out of the list if there are no non-weak references
to the car of the cons.
If you are experimenting with weak references
interactively, remember that an object is not dead if it was
returned by one of the last three interactively-evaluated
expressions, because of the variables *
,
**
, and ***
. The easy
workaround is to evaluate some meaningless expression before
invoking gc
, to get the object out of the
REPL variables.
Previous Section | Next Section | Table of Contents | Glossary | Index |