Skip to content

Instantly share code, notes, and snippets.

@abhin4v
Created May 11, 2016 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhin4v/6b7494df258361233d62a9d976e135e5 to your computer and use it in GitHub Desktop.
Save abhin4v/6b7494df258361233d62a9d976e135e5 to your computer and use it in GitHub Desktop.
A clojure wrapper over Google Guava Cache
(ns guava-cache
(:refer-clojure :exclude [get])
(:import [com.google.common.cache Cache CacheBuilder]
(java.util Map)))
(defn create [cache-spec]
(.build (CacheBuilder/from ^String cache-spec)))
(def ^:private nil-sentinal "ABC_NIL_SENTINAL_XYZ")
(defn get
([^Cache cache key]
(let [value (.getIfPresent cache key)]
(if-not (= value nil-sentinal)
value
nil)))
([^Cache cache key loader-fn]
(let [value (.get cache key (fn [] (if-let [value (loader-fn)]
value
nil-sentinal)))]
(if-not (= value nil-sentinal)
value
nil))))
(defn put
([^Cache cache key val]
(.put cache key val))
([^Cache cache ^Map map]
(.putAll cache map)))
(defn invalidate
([^Cache cache]
(.invalidateAll cache))
([^Cache cache key]
(.invalidate cache key)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment