Skip to content

Instantly share code, notes, and snippets.

@SerhiiKozachenko
Forked from lnostdal/cachebuilder.clj
Created July 14, 2024 14:21
Show Gist options
  • Save SerhiiKozachenko/065046ed0b92872763c12c7b168f8df8 to your computer and use it in GitHub Desktop.
Save SerhiiKozachenko/065046ed0b92872763c12c7b168f8df8 to your computer and use it in GitHub Desktop.
Guava: CacheBuilder / CacheLoader for compute cache type thing and similar
;; This stuff is pretty useful in many contexts.
...
(:import (com.google.common.cache CacheBuilder CacheLoader))
...
quantataraxia.core> (with (-> (CacheBuilder/newBuilder)
(.weakKeys)
(.concurrencyLevel (.availableProcessors (Runtime/getRuntime)))
(.build (proxy [CacheLoader] []
(load [k]
21))))
(.put it :answer 42)
(dbg-prin1 (.get it :answer))
(dbg-prin1 (.get it :something-else))
(dbg-prin1 (.get it :blah (fn [] 3.1415))))
(.get it :answer) => 42
(.get it :something-else) => 21
(.get it :blah (fn [] 3.1415)) => 3.1415
;;;
;;;
quantataraxia.core> (with (-> (CacheBuilder/newBuilder)
(.weakKeys)
(.concurrencyLevel (.availableProcessors (Runtime/getRuntime)))
(.build #_(proxy [CacheLoader] []
(load [k]
21))))
(.put it :answer 42)
(dbg-prin1 (.getIfPresent it :answer))
(dbg-prin1 (.getIfPresent it :something-else))
(dbg-prin1 (.get it :blah (fn [] (println "whot!") 3.1415)))
(dbg-prin1 (.get it :blah (fn [] (println "whot!") 3.1415))))
(.getIfPresent it :answer) => 42
(.getIfPresent it :something-else) => nil
whot!
(.get it :blah (fn [] (println whot!) 3.1415)) => 3.1415
(.get it :blah (fn [] (println whot!) 3.1415)) => 3.1415
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment