17Write-through cache

A write-through cache is essentially a hash table that calls user supplied functions to load and store data from a back-end store (a database, file, network resource or other). This is useful for, for example, caching database values so that writes are always sent to the database (so it is always up-to-date) but data is only loaded as needed.

The cache associates a fixed life-span to all stored data, so data in the cache will eventually be removed. This ensures data is the cache does not get too old, and additionally that memory consumption is constrained.

Creates a write-through cache using the given load-proc and store-proc and equal? has a key comparison function.

load-proc is called by cache-ref when there is no cached value for a given key. It is passed the key and must return the corresponding value from the back-end store. cache-ref updates the cache with the loaded value: subsequent requests for the same key will not trigger load-proc until the cached value expires.

store-proc is called by cache-set!. It is passed a key and value and must update the back-end store. cache-set! updates the cache automatically.

The optional expire-proc is called immediately after a value is removed from the cache (either manually or through natural expiry). The function is passed a reference to the cache, the key and the expiring value. The default function does nothing but user-supplied functions can, for example, add the data back to the cache or re-query the back-end store.

The optional lifetime specifies the number of seconds that each item is stored in the cache.

Items are expired in two ways:

a thread makes sweeps of the entire cache once every (/lifetime2) seconds;

cache-ref checks if a requested key has expired since the most recent sweep.

Retrieves a value from cache. If the cache contains a value for key, the value is returned immediately. If the cache does not contain a value for key (or the value has recently expired; see make-cache for more information), its load-proc is called to retrieve the value from its back-end store.