Skip to content

Commit

Permalink
Fixed TTL cache lookup of expired items
Browse files Browse the repository at this point in the history
  • Loading branch information
fogus committed Jul 23, 2012
1 parent c5352fe commit 0f92a22
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
15 changes: 9 additions & 6 deletions src/main/clojure/clojure/core/cache.clj
Expand Up @@ -231,17 +231,20 @@


(defn- key-killer
[ttl limit now]
(let [ks (map key (filter #(> (- now (val %)) limit) ttl))]
[ttl expiry now]
(let [ks (map key (filter #(> (- now (val %)) expiry) ttl))]
#(apply dissoc % ks)))


(defcache TTLCache [cache ttl ttl-ms]
CacheProtocol
(lookup [_ item]
(get cache item))
(lookup [_ item not-found]
(get cache item not-found))
(lookup [this item]
(let [ret (lookup this item ::nope)]
(when-not (= ret ::nope) ret)))
(lookup [this item not-found]
(if (has? this item)
(get cache item)
not-found))
(has? [_ item]
(let [t (get ttl item (- ttl-ms))]
(< (- (System/currentTimeMillis)
Expand Down
14 changes: 12 additions & 2 deletions src/test/clojure/clojure/core/cache/tests.clj
Expand Up @@ -203,7 +203,10 @@
(let [C (ttl-cache-factory {} :ttl 500)]
(are [x y] (= x y)
{:a 1, :b 2} (-> C (assoc :a 1) (assoc :b 2) .cache)
{:c 3} (-> C (assoc :a 1) (assoc :b 2) (sleepy 700) (assoc :c 3) .cache)))))
{:c 3} (-> C (assoc :a 1) (assoc :b 2) (sleepy 700) (assoc :c 3) .cache))))
(testing "TTL cache does not return a value that has expired."
(let [C (ttl-cache-factory {} :ttl 500)]
(is (nil? (-> C (assoc :a 1) (sleepy 700) (lookup :a)))))))

(deftest test-lu-cache-ilookup
(testing "that the LUCache can lookup via keywords"
Expand Down Expand Up @@ -242,7 +245,14 @@
(assoc :c 4)
(assoc :d 5)
(assoc :e 6))
{:e 6, :d 5, :b 3}))))
{:e 6, :d 5, :b 3}))

(is (= {:a 1 :b 3}
(-> (clojure.core.cache/lu-cache-factory {} :threshold 2)
(assoc :a 1)
(assoc :b 2)
(assoc :b 3)
.cache)))))

;; # LIRS

Expand Down

0 comments on commit 0f92a22

Please sign in to comment.