Previous Section Next Section Table of Contents Glossary Index

Chapter 15. Understanding and Configuring the Garbage Collector

15.5. Weak Hash Tables

In general, a "weak reference" is a reference to an object which will 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. You may want this behavior. If you don't, you need weak references.

CCL supports weak references with "weak hash tables". 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 other 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.

If you are experimenting with weak hash tables 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