Previous: , Up: Hash Tables   [Contents][Index]


54.3 Weak Hash Tables

A weak hash table is a special variety of hash table whose elements do not count as GC referents. For any key-value pair in such a hash table, if either the key or value (or in some cases, if one particular one of the two) has no references to it outside of weak hash tables (and similar structures such as weak lists), the pair will be removed from the table, and the key and value collected. A non-weak hash table (or any other pointer) would prevent the objects from being collected.

Weak hash tables are useful for keeping track of information in a non-obtrusive way, for example to implement caching. If the cache contains objects such as buffers, markers, image instances, etc. that will eventually disappear and get garbage-collected, using a weak hash table ensures that these objects are collected normally rather than remaining around forever, long past their actual period of use. (Otherwise, you’d have to explicitly map over the hash table every so often and remove unnecessary elements.)

There are four types of weak hash tables:

key-and-value-weak hash tables

In these hash tables, also known as fully weak or simply as weak hash tables, a pair disappears if either the key or the value is unreferenced outside of the table.

key-weak hash tables

In these hash tables, a pair disappears if the key is unreferenced outside of the table, regardless of how the value is referenced.

value-weak hash tables

In these hash tables, a pair disappears if the value is unreferenced outside of the table, regardless of how the key is referenced.

key-or-value-weak hash tables

In these hash tables, a pair disappears if both the key and the value are unreferenced outside of the table.

Also see Weak Lists.

Weak hash tables are created by specifying the :weakness keyword to make-hash-table.


Previous: , Up: Hash Tables   [Contents][Index]