Skip to content
fogus edited this page Mar 14, 2012 · 5 revisions

TTL cache

The time-to-live cache is one that evicts items that are older than a time threshold (in milliseconds).

General usage

To create a core.cache TTLCache instance you can do the following:

    (ns your.lib 
      (:require [clojure.core.cache :as cache]))
	
    (def C (cache/ttl-cache-factory {} :ttl 1000))
    
    (-> C (assoc :a 1) (assoc :b 2))
	;=> {:a 1, :b 2}

At this point the cache is fresh and younger than one second (depending on how fast you read that is), but if you execute yet another call the story will change:

    (defn sleepy [e t] (Thread/sleep t) e)
    
    (-> C (assoc :a 1) 
	      (assoc :b 2)
		  (sleepy 1500)
	      (assoc :c 3))
	;=> {:c 3}

At this point the operation of the TTL cache is exposed. As you see, sleeping in between adding the keys :a and :b causes them to be evicted on the next insertion.

LU cache use cases

TODO

Clone this wiki locally