Skip to content
fogus edited this page Mar 13, 2012 · 9 revisions

LU cache

The least-used cache is one that evicts items that are used least frequently once its limit has been exceeded.

General usage

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

(ns your.lib 
  (:require [clojure.core.cache :as cache]))

(def C (cache/lu-cache-factory {} :limit 2))

(-> C (assoc :a 1) (assoc :b 2))
;=> {:a 1, :b 2}

At this point the cache has not yet crossed the set limit of 2, but if you execute yet another call the story will change:

(-> C (assoc :a 1) (assoc :b 2) (assoc :c 3))
;=> {:b 2, :c 3}

At this point the operation of the LRU cache looks exactly the same at the FIFO cache. However, the difference becomes apparent when a given cache item is "touched":

(-> C (assoc :a 1) 
      (assoc :b 2)
      (.hit :b)
      (.hit :b)
      (.hit :a)       ;; ensure :a is used most recently
      (assoc :c 3))

;=> {:c 3, :b 2}

As you see, hitting the key :b twice marks it as more important that :a even though the latter was "touched" more recently. That is, when the threshold is passed, the cache will expel the Least Used element in favor of the element accessed most often.

LU cache use cases

TODO

Clone this wiki locally