Liking cljdoc? Tell your friends :D


Clojure library for memoization of the single value.

Clojars Project

Design goals

  • Simple utility for caching single value accessed from concurrent threads.
  • Lazy initialization of the cached value on access.
  • Performant access to the cached value.
  • Optional cache expiration.
  • Native implementation without external dependencies.

Basic usage

(ns readme.manual
  "Example of using of the manual cache."
  (:require [strojure.memoize-one.core :as memoize]
            [strojure.memoize-one.manual-cache :as cache]))

(defn- test-cache
  (cache/memoize (fn [] (let [v (System/currentTimeMillis)]
                          (println (str "Create val " v " " (rand-int 100)))

  (let [c (test-cache #(Thread/sleep 100))]
    (dotimes [i 10]
        (Thread/sleep (* i 50))
        (let [v (memoize/get-ref c)]
          (memoize/evict v)))))

  (def c (test-cache #(Thread/sleep 100)))
  (def c (test-cache #(when (pos? (rand-int 2)) (throw (Exception. "Oops")))))

  (memoize/get-ref c)

  (deref (memoize/get-ref c))                     ; Execution time mean : 7.299272 ns

  (.deref (memoize/get-ref c))                    ; Execution time mean : 6.074256 ns

  (memoize/get-value c)                           ; Execution time mean : 6.343759 ns

  (doto (memoize/get-ref c) (deref) (memoize/evict))

(ns readme.expiring
  "Example of using of the expiring cache."
  (:require [strojure.memoize-one.core :as memoize]
            [strojure.memoize-one.expiring-cache :as cache]))

(def ^:private test-fn
  (fn []
    (let [v (System/currentTimeMillis)]
      (println (str "Create val " v " " (rand-int 100)))
      (Thread/sleep 100)
      #_(when (pos? (rand-int 2))
          (throw (Exception. "Oops")))

(def ttl-cache
  "TTL cache for 20 seconds."
  (cache/memoize-ttl 20000 test-fn))

  (deref (memoize/get-ref ttl-cache))             ; Execution time mean : 17,081336 ns
  ;Create val 1654094164999 12
  (memoize/evict (memoize/get-ref ttl-cache))

(defn- odd-test-fn
  (fn [] (odd? x)))

(def odd-cache
  "Cache expiring using `odd-test-fn`."
  (cache/memoize-with odd-test-fn test-fn))

  (deref (memoize/get-ref odd-cache))             ; Execution time mean : 16,548488 ns
  ;Create val 1654094271591 0
  (memoize/evict (memoize/get-ref odd-cache))

(defn- combined-test-fn
  "Expiration test for TTL or `odd`."
  (fn [x] (let [p1 ((cache/ttl-test-fn ttl) x)
                p2 (odd-test-fn x)]
            (fn []
              (or (p1) (p2))))))

(def combined-cache
  "Cache expiring using `combined-test-fn`."
  (cache/memoize-with (combined-test-fn 20000) test-fn))

  (deref (memoize/get-ref combined-cache))        ; Execution time mean : 26,168754 ns
  ;Create val 1654094360990 6
  (memoize/evict (memoize/get-ref combined-cache))

Can you improve this documentation?Edit on GitHub

cljdoc is a website building & hosting documentation for Clojure/Script libraries

× close