根据使用 core.memoize 的建议,这样可以按预期工作
(let [thread-count 20
invocations-counter (atom 0)
expensive-function (fn [k]
(swap! invocations-counter inc)
(Thread/sleep 3000)
(str "value-" k))
cache (-> {}
(cache/ttl-cache-factory :ttl 120000)
(cache/lu-cache-factory :threshold 100))
memoized-function (memoize/memoizer expensive-function cache)
latch (java.util.concurrent.CountDownLatch. thread-count)]
(&doseq [i (range thread-count)]
(&println "starting thread" i)
(&.start (Thread. (&fn []
(&memoized-function "my-key"))
(&.countDown latch)))))
(&.await latch)
(&assert (= 1 (deref invocations-counter))))