` section:
org.clojure
core.cache
0.6.2
Enjoy!
Places
------
* [Source code](https://github.com/clojure/core.cache)
* [Ticket system](http://clojure.atlassian.net/browse/CCACHE)
* [Announcement](http://groups.google.com/group/clojure/browse_frm/thread/69d08572ab265dc7)
* [API Reference](https://clojure.github.com/core.cache)
* [Examples and documentation](https://github.com/clojure/core.cache/wiki) (work in progress)
Changes from v0.6.1
-------------------
The v0.6.2 version of core.cache contains the following changes:
* Removed reflection warnings.
* Bug fix for LRU, LU and TTL caches disabling the eviction of duplicate keys prior to a threshold less than three.
* FIFOCache respects threshold prior to applying its eviction policy.
Plans
-----
The following capabilities are under design, development, or consideration for future versions of core.cache:
* More speed!
* Make ClojureScript compatible
* Asynchronous caching protocol
* FunCache implementation
* `LIRSCache evict`
* Hardening of the `seed` function implementations
* test.generative usage
* Deprecation of Clache
* More documentation and examples
More planning is needed around capabilities not listed nor thought of. core.cache-core.cache-1.0.207/epl-v10.html 0000664 0000000 0000000 00000030560 13644155620 0017727 0 ustar 00root root 0000000 0000000
Eclipse Public License - Version 1.0
Eclipse Public License - v 1.0
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR
DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS
AGREEMENT.
1. DEFINITIONS
"Contribution" means:
a) in the case of the initial Contributor, the initial
code and documentation distributed under this Agreement, and
b) in the case of each subsequent Contributor:
i) changes to the Program, and
ii) additions to the Program;
where such changes and/or additions to the Program
originate from and are distributed by that particular Contributor. A
Contribution 'originates' from a Contributor if it was added to the
Program by such Contributor itself or anyone acting on such
Contributor's behalf. Contributions do not include additions to the
Program which: (i) are separate modules of software distributed in
conjunction with the Program under their own license agreement, and (ii)
are not derivative works of the Program.
"Contributor" means any person or entity that distributes
the Program.
"Licensed Patents" mean patent claims licensable by a
Contributor which are necessarily infringed by the use or sale of its
Contribution alone or when combined with the Program.
"Program" means the Contributions distributed in accordance
with this Agreement.
"Recipient" means anyone who receives the Program under
this Agreement, including all Contributors.
2. GRANT OF RIGHTS
a) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a non-exclusive, worldwide,
royalty-free copyright license to reproduce, prepare derivative works
of, publicly display, publicly perform, distribute and sublicense the
Contribution of such Contributor, if any, and such derivative works, in
source code and object code form.
b) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a non-exclusive, worldwide,
royalty-free patent license under Licensed Patents to make, use, sell,
offer to sell, import and otherwise transfer the Contribution of such
Contributor, if any, in source code and object code form. This patent
license shall apply to the combination of the Contribution and the
Program if, at the time the Contribution is added by the Contributor,
such addition of the Contribution causes such combination to be covered
by the Licensed Patents. The patent license shall not apply to any other
combinations which include the Contribution. No hardware per se is
licensed hereunder.
c) Recipient understands that although each Contributor
grants the licenses to its Contributions set forth herein, no assurances
are provided by any Contributor that the Program does not infringe the
patent or other intellectual property rights of any other entity. Each
Contributor disclaims any liability to Recipient for claims brought by
any other entity based on infringement of intellectual property rights
or otherwise. As a condition to exercising the rights and licenses
granted hereunder, each Recipient hereby assumes sole responsibility to
secure any other intellectual property rights needed, if any. For
example, if a third party patent license is required to allow Recipient
to distribute the Program, it is Recipient's responsibility to acquire
that license before distributing the Program.
d) Each Contributor represents that to its knowledge it
has sufficient copyright rights in its Contribution, if any, to grant
the copyright license set forth in this Agreement.
3. REQUIREMENTS
A Contributor may choose to distribute the Program in object code
form under its own license agreement, provided that:
a) it complies with the terms and conditions of this
Agreement; and
b) its license agreement:
i) effectively disclaims on behalf of all Contributors
all warranties and conditions, express and implied, including warranties
or conditions of title and non-infringement, and implied warranties or
conditions of merchantability and fitness for a particular purpose;
ii) effectively excludes on behalf of all Contributors
all liability for damages, including direct, indirect, special,
incidental and consequential damages, such as lost profits;
iii) states that any provisions which differ from this
Agreement are offered by that Contributor alone and not by any other
party; and
iv) states that source code for the Program is available
from such Contributor, and informs licensees how to obtain it in a
reasonable manner on or through a medium customarily used for software
exchange.
When the Program is made available in source code form:
a) it must be made available under this Agreement; and
b) a copy of this Agreement must be included with each
copy of the Program.
Contributors may not remove or alter any copyright notices contained
within the Program.
Each Contributor must identify itself as the originator of its
Contribution, if any, in a manner that reasonably allows subsequent
Recipients to identify the originator of the Contribution.
4. COMMERCIAL DISTRIBUTION
Commercial distributors of software may accept certain
responsibilities with respect to end users, business partners and the
like. While this license is intended to facilitate the commercial use of
the Program, the Contributor who includes the Program in a commercial
product offering should do so in a manner which does not create
potential liability for other Contributors. Therefore, if a Contributor
includes the Program in a commercial product offering, such Contributor
("Commercial Contributor") hereby agrees to defend and
indemnify every other Contributor ("Indemnified Contributor")
against any losses, damages and costs (collectively "Losses")
arising from claims, lawsuits and other legal actions brought by a third
party against the Indemnified Contributor to the extent caused by the
acts or omissions of such Commercial Contributor in connection with its
distribution of the Program in a commercial product offering. The
obligations in this section do not apply to any claims or Losses
relating to any actual or alleged intellectual property infringement. In
order to qualify, an Indemnified Contributor must: a) promptly notify
the Commercial Contributor in writing of such claim, and b) allow the
Commercial Contributor to control, and cooperate with the Commercial
Contributor in, the defense and any related settlement negotiations. The
Indemnified Contributor may participate in any such claim at its own
expense.
For example, a Contributor might include the Program in a commercial
product offering, Product X. That Contributor is then a Commercial
Contributor. If that Commercial Contributor then makes performance
claims, or offers warranties related to Product X, those performance
claims and warranties are such Commercial Contributor's responsibility
alone. Under this section, the Commercial Contributor would have to
defend claims against the other Contributors related to those
performance claims and warranties, and if a court requires any other
Contributor to pay any damages as a result, the Commercial Contributor
must pay those damages.
5. NO WARRANTY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS
PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION,
ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY
OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
responsible for determining the appropriateness of using and
distributing the Program and assumes all risks associated with its
exercise of rights under this Agreement , including but not limited to
the risks and costs of program errors, compliance with applicable laws,
damage to or loss of data, programs or equipment, and unavailability or
interruption of operations.
6. DISCLAIMER OF LIABILITY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT
NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. GENERAL
If any provision of this Agreement is invalid or unenforceable under
applicable law, it shall not affect the validity or enforceability of
the remainder of the terms of this Agreement, and without further action
by the parties hereto, such provision shall be reformed to the minimum
extent necessary to make such provision valid and enforceable.
If Recipient institutes patent litigation against any entity
(including a cross-claim or counterclaim in a lawsuit) alleging that the
Program itself (excluding combinations of the Program with other
software or hardware) infringes such Recipient's patent(s), then such
Recipient's rights granted under Section 2(b) shall terminate as of the
date such litigation is filed.
All Recipient's rights under this Agreement shall terminate if it
fails to comply with any of the material terms or conditions of this
Agreement and does not cure such failure in a reasonable period of time
after becoming aware of such noncompliance. If all Recipient's rights
under this Agreement terminate, Recipient agrees to cease use and
distribution of the Program as soon as reasonably practicable. However,
Recipient's obligations under this Agreement and any licenses granted by
Recipient relating to the Program shall continue and survive.
Everyone is permitted to copy and distribute copies of this
Agreement, but in order to avoid inconsistency the Agreement is
copyrighted and may only be modified in the following manner. The
Agreement Steward reserves the right to publish new versions (including
revisions) of this Agreement from time to time. No one other than the
Agreement Steward has the right to modify this Agreement. The Eclipse
Foundation is the initial Agreement Steward. The Eclipse Foundation may
assign the responsibility to serve as the Agreement Steward to a
suitable separate entity. Each new version of the Agreement will be
given a distinguishing version number. The Program (including
Contributions) may always be distributed subject to the version of the
Agreement under which it was received. In addition, after a new version
of the Agreement is published, Contributor may elect to distribute the
Program (including its Contributions) under the new version. Except as
expressly stated in Sections 2(a) and 2(b) above, Recipient receives no
rights or licenses to the intellectual property of any Contributor under
this Agreement, whether expressly, by implication, estoppel or
otherwise. All rights in the Program not expressly granted under this
Agreement are reserved.
This Agreement is governed by the laws of the State of New York and
the intellectual property laws of the United States of America. No party
to this Agreement will bring a legal action under this Agreement more
than one year after the cause of action arose. Each party waives its
rights to a jury trial in any resulting litigation.
core.cache-core.cache-1.0.207/pom.xml 0000664 0000000 0000000 00000002707 13644155620 0017174 0 ustar 00root root 0000000 0000000
4.0.0
core.cache
1.0.207
core.cache
Cache library for Clojure.
scm:git:git://github.com/clojure/core.cache.git
scm:git:ssh://git@github.com/clojure/core.cache.git
core.cache-1.0.207
https://github.com/clojure/core.cache
Eclipse Public License 1.0
http://opensource.org/licenses/eclipse-1.0.php
repo
org.clojure
pom.contrib
1.0.0
fogus
Michael Fogus
http://www.fogus.me
1.6.0
org.clojure
data.priority-map
1.0.0
core.cache-core.cache-1.0.207/run-tests.sh 0000775 0000000 0000000 00000000152 13644155620 0020152 0 ustar 00root root 0000000 0000000 #!/bin/sh
versions="1.6 1.7 1.8 1.9 1.10 master"
for v in $versions
do
time clj -A:test:runner:$v
done
core.cache-core.cache-1.0.207/src/ 0000775 0000000 0000000 00000000000 13644155620 0016440 5 ustar 00root root 0000000 0000000 core.cache-core.cache-1.0.207/src/main/ 0000775 0000000 0000000 00000000000 13644155620 0017364 5 ustar 00root root 0000000 0000000 core.cache-core.cache-1.0.207/src/main/clojure/ 0000775 0000000 0000000 00000000000 13644155620 0021027 5 ustar 00root root 0000000 0000000 core.cache-core.cache-1.0.207/src/main/clojure/clojure/ 0000775 0000000 0000000 00000000000 13644155620 0022472 5 ustar 00root root 0000000 0000000 core.cache-core.cache-1.0.207/src/main/clojure/clojure/core/ 0000775 0000000 0000000 00000000000 13644155620 0023422 5 ustar 00root root 0000000 0000000 core.cache-core.cache-1.0.207/src/main/clojure/clojure/core/cache.clj 0000664 0000000 0000000 00000054316 13644155620 0025170 0 ustar 00root root 0000000 0000000 ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns ^{:doc "A caching library for Clojure."
:author "Fogus"}
clojure.core.cache
(:require clojure.data.priority-map)
(:import (java.lang.ref ReferenceQueue SoftReference)
(java.util.concurrent ConcurrentHashMap)))
(set! *warn-on-reflection* true)
;; # Protocols and Types
(defprotocol CacheProtocol
"This is the protocol describing the basic cache capability."
(lookup [cache e]
[cache e not-found]
"Retrieve the value associated with `e` if it exists, else `nil` in
the 2-arg case. Retrieve the value associated with `e` if it exists,
else `not-found` in the 3-arg case.")
(has? [cache e]
"Checks if the cache contains a value associated with `e`")
(hit [cache e]
"Is meant to be called if the cache is determined to contain a value
associated with `e`")
(miss [cache e ret]
"Is meant to be called if the cache is determined to **not** contain a
value associated with `e`")
(evict [cache e]
"Removes an entry from the cache")
(seed [cache base]
"Is used to signal that the cache should be created with a seed.
The contract is that said cache should return an instance of its
own type."))
(def ^{:private true} default-wrapper-fn #(%1 %2))
(defn through
"The basic hit/miss logic for the cache system. Expects a wrap function and
value function. The wrap function takes the value function and the item in question
and is expected to run the value function with the item whenever a cache
miss occurs. The intent is to hide any cache-specific cells from leaking
into the cache logic itelf."
([cache item] (through default-wrapper-fn identity cache item))
([value-fn cache item] (through default-wrapper-fn value-fn cache item))
([wrap-fn value-fn cache item]
(if (clojure.core.cache/has? cache item)
(clojure.core.cache/hit cache item)
(clojure.core.cache/miss cache item (wrap-fn #(value-fn %) item)))))
(defn through-cache
"The basic hit/miss logic for the cache system. Like through but always has
the cache argument in the first position for easier use with swap! etc."
([cache item] (through-cache cache item default-wrapper-fn identity))
([cache item value-fn] (through-cache cache item default-wrapper-fn value-fn))
([cache item wrap-fn value-fn]
(if (clojure.core.cache/has? cache item)
(clojure.core.cache/hit cache item)
(clojure.core.cache/miss cache item (wrap-fn #(value-fn %) item)))))
(defmacro defcache
[type-name fields & specifics]
(let [[base & _] fields
base-field (with-meta base {:tag 'clojure.lang.IPersistentMap})]
`(deftype ~type-name [~@fields]
~@specifics
clojure.lang.ILookup
(valAt [this# key#]
(lookup this# key#))
(valAt [this# key# not-found#]
(if (has? this# key#)
(lookup this# key#)
not-found#))
java.lang.Iterable
(iterator [_#]
(.iterator ~base-field))
clojure.lang.IPersistentMap
(assoc [this# k# v#]
(miss this# k# v#))
(without [this# k#]
(evict this# k#))
clojure.lang.Associative
(containsKey [this# k#]
(has? this# k#))
(entryAt [this# k#]
(when (has? this# k#)
(clojure.lang.MapEntry. k# (lookup this# k#))))
clojure.lang.Counted
(count [this#]
(count ~base-field))
clojure.lang.IPersistentCollection
(cons [this# elem#]
(seed this# (conj ~base-field elem#)))
(empty [this#]
(seed this# (empty ~base-field)))
(equiv [this# other#]
(= other# ~base-field))
clojure.lang.Seqable
(seq [_#]
(seq ~base-field)))))
(defcache BasicCache [cache]
CacheProtocol
(lookup [_ item]
(get cache item))
(lookup [_ item not-found]
(get cache item not-found))
(has? [_ item]
(contains? cache item))
(hit [this item] this)
(miss [_ item result]
(BasicCache. (assoc cache item result)))
(evict [_ key]
(BasicCache. (dissoc cache key)))
(seed [_ base]
(BasicCache. base))
Object
(toString [_] (str cache)))
;; FnCache
(defcache FnCache [cache f]
CacheProtocol
(lookup [_ item]
(f (get cache item)))
(lookup [_ item not-found]
(let [ret (get cache item not-found)]
(if (= not-found ret)
not-found
(f ret))))
(has? [_ item]
(contains? cache item))
(hit [this item] this)
(miss [_ item result]
(BasicCache. (assoc cache item result)))
(evict [_ key]
(BasicCache. (dissoc cache key)))
(seed [_ base]
(BasicCache. base))
Object
(toString [_] (str cache)))
;; # FIFO
(defn- describe-layout [mappy limit]
(let [ks (keys mappy)
[dropping keeping] (split-at (- (count ks) limit) ks)]
{:dropping dropping
:keeping keeping
:queue
(-> clojure.lang.PersistentQueue/EMPTY
(into (repeat (- limit (count keeping)) ::free))
(into (take limit keeping)))}))
(defn- prune-queue [q k]
(reduce (fn [q e] (if (#{k} e) q (conj q e)))
(conj clojure.lang.PersistentQueue/EMPTY ::free)
q))
(defcache FIFOCache [cache q limit]
CacheProtocol
(lookup [_ item]
(get cache item))
(lookup [_ item not-found]
(get cache item not-found))
(has? [_ item]
(contains? cache item))
(hit [this item]
this)
(miss [_ item result]
(let [[kache qq] (let [k (peek q)]
(if (>= (count cache) limit)
[(dissoc cache k) (pop q)]
[cache (pop q)]))]
(FIFOCache. (assoc kache item result)
(conj qq item)
limit)))
(evict [this key]
(if (contains? cache key)
(FIFOCache. (dissoc cache key)
(prune-queue q key)
limit)
this))
(seed [_ base]
(let [{dropping :dropping
q :queue} (describe-layout base limit)]
(FIFOCache. (apply dissoc base dropping)
q
limit)))
Object
(toString [_]
(str cache \, \space (pr-str q))))
(defn- build-leastness-queue
[base limit start-at]
(into (clojure.data.priority-map/priority-map)
(concat (take (- limit (count base)) (for [k (range (- limit) 0)] [k k]))
(for [[k _] base] [k start-at]))))
(defcache LRUCache [cache lru tick limit]
CacheProtocol
(lookup [_ item]
(get cache item))
(lookup [_ item not-found]
(get cache item not-found))
(has? [_ item]
(contains? cache item))
(hit [_ item]
(let [tick+ (inc tick)]
(LRUCache. cache
(if (contains? cache item)
(assoc lru item tick+)
lru)
tick+
limit)))
(miss [_ item result]
(let [tick+ (inc tick)]
(if (>= (count lru) limit)
(let [k (if (contains? lru item)
item
(first (peek lru))) ;; minimum-key, maybe evict case
c (-> cache (dissoc k) (assoc item result))
l (-> lru (dissoc k) (assoc item tick+))]
(LRUCache. c l tick+ limit))
(LRUCache. (assoc cache item result) ;; no change case
(assoc lru item tick+)
tick+
limit))))
(evict [this key]
(if (contains? cache key)
(LRUCache. (dissoc cache key)
(dissoc lru key)
(inc tick)
limit)
this))
(seed [_ base]
(LRUCache. base
(build-leastness-queue base limit 0)
0
limit))
Object
(toString [_]
(str cache \, \space lru \, \space tick \, \space limit)))
(defn- key-killer-q
[ttl q expiry now]
(let [[ks q'] (reduce (fn [[ks q] [k g t]]
(if (> (- now t) expiry)
(if (= g (first (get ttl k)))
[(conj ks k) (pop q)]
[ks (pop q)])
(reduced [ks q])))
[[] q]
q)]
[#(apply dissoc % ks) q']))
(defcache TTLCacheQ [cache ttl q gen ttl-ms]
CacheProtocol
(lookup [this item]
(let [ret (lookup this item ::nope)]
(when-not (= ::nope ret) ret)))
(lookup [this item not-found]
(if (has? this item)
(get cache item)
not-found))
(has? [_ item]
(and (let [[_ t] (get ttl item [0 (- ttl-ms)])]
(< (- (System/currentTimeMillis)
t)
ttl-ms))
(contains? cache item)))
(hit [this item] this)
(miss [this item result]
(let [now (System/currentTimeMillis)
[kill-old q'] (key-killer-q ttl q ttl-ms now)]
(TTLCacheQ. (assoc (kill-old cache) item result)
(assoc (kill-old ttl) item [gen now])
(conj q' [item gen now])
(unchecked-inc gen)
ttl-ms)))
(seed [_ base]
(let [now (System/currentTimeMillis)]
(TTLCacheQ. base
;; we seed the cache all at gen, but subsequent entries
;; will get gen+1, gen+2 etc
(into {} (for [x base] [(key x) [gen now]]))
(into q (for [x base] [(key x) gen now]))
(unchecked-inc gen)
ttl-ms)))
(evict [_ key]
(TTLCacheQ. (dissoc cache key)
(dissoc ttl key)
q
gen
ttl-ms))
Object
(toString [_]
(str cache \, \space ttl \, \space ttl-ms)))
(defcache LUCache [cache lu limit]
CacheProtocol
(lookup [_ item]
(get cache item))
(lookup [_ item not-found]
(get cache item not-found))
(has? [_ item]
(contains? cache item))
(hit [_ item]
(LUCache. cache (update-in lu [item] inc) limit))
(miss [_ item result]
(if (>= (count lu) limit) ;; need to evict?
(let [min-key (if (contains? lu item)
::nope
(first (peek lu))) ;; maybe evict case
c (-> cache (dissoc min-key) (assoc item result))
l (-> lu (dissoc min-key) (update-in [item] (fnil inc 0)))]
(LUCache. c l limit))
(LUCache. (assoc cache item result) ;; no change case
(assoc lu item 0)
limit)))
(evict [this key]
(if (contains? this key)
(LUCache. (dissoc cache key)
(dissoc lu key)
limit)
this))
(seed [_ base]
(LUCache. base
(build-leastness-queue base limit 0)
limit))
Object
(toString [_]
(str cache \, \space lu \, \space limit)))
;; # LIRS
;; *initial Clojure implementation by Jan Oberhagemann*
;; A
;; [LIRS](http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.116.2184)
;; cache consists of two LRU lists, `S` and `Q`, and keeps more history
;; than a LRU cache. Every cached item is either a LIR, HIR or
;; non-resident HIR block. `Q` contains only HIR blocks, `S` contains
;; LIR, HIR, non-resident HIR blocks. The total cache size is
;; |`S`|+|`Q`|, |`S`| is typically 99% of the cache size.
;; * LIR block:
;; Low Inter-Reference block, a cached item with a short interval
;; between accesses. A block `x`, `x` ∈ `S` ∧ `x` ∉ `Q` ∧ `x` ∈
;; `cache`, is a LIR block.
;; * HIR block:
;; High Inter-Reference block, a cached item with rare accesses and
;; long interval. A block `x`, `x` ∈ `Q` ∧ `x` ∈ `cache`, is a HIR block.
;; * non-resident HIR block:
;; only the key of the HIR block is cached, without the corresponding
;; value a test (has?) for the corresponding key is always a
;; miss. Used for additional history information. A block `x`, `x` ∈
;; `S` ∧ `x` ∉ `Q` ∧ `x` ∉ `cache`, is a non-resident HIR block.
;; ## Outline of the implemented algorithm
;; `cache` is used to store the key value pairs.
;; `S` and `Q` maintain the relative order of accesses of the keys, like
;; a LRU list.
;; Definition of `prune stack`:
;;
;; repeatedly remove oldest item from S until an item k, k ∉ Q ∧
;; k ∈ cache (a LIR block), is found
;; In case of a miss for key `k` and value `v` (`k` ∉ cache) and
;;
;; * (1.1) `S` is not filled, |`S`| < `limitS`
;; add k to S
;; add k to the cache
;; * (1.2) `k` ∉ `S`, never seen or not seen for a long, long time
;; remove oldest item x from Q
;; remove x from cache
;; add k to S
;; add k to Q
;; add k to the cache
;; * (1.3) `k` ∈ `S`, this is a non-resident HIR block
;; remove oldest item x from Q
;; remove x from cache
;; add k to S
;; remove oldest item y from S
;; add y to Q
;; prune stack
;; In case of a hit for key `k` (`k` ∈ cache) and
;; * (2.1) `k` ∈ `S` ∧ `k` ∉ `Q`, a LIR block
;; add k to S / refresh
;; prune stack if k was the oldest item in S
;; * (2.2) `k` ∈ `S` ∧ `k` ∈ `Q`, a HIR block
;; add k to S / refresh
;; remove k from Q
;; remove oldest item x from S
;; add x to Q
;; prune stack
;; * (2.3) `k` ∉ `S` ∧ `k` ∈ `Q`, a HIR block, only older than the oldest item in S
;; add k to S
;; add k to Q / refresh
(defn- prune-stack [lruS lruQ cache]
(loop [s lruS q lruQ c cache]
(let [k (apply min-key s (keys s))]
(if (or (contains? q k) ; HIR item
(not (contains? c k))) ; non-resident HIR item
(recur (dissoc s k) q c)
s))))
(defcache LIRSCache [cache lruS lruQ tick limitS limitQ]
CacheProtocol
(lookup [_ item]
(get cache item))
(lookup [_ item not-found]
(get cache item not-found))
(has? [_ item]
(contains? cache item))
(hit [_ item]
(let [tick+ (inc tick)]
(if (not (contains? lruS item))
; (2.3) item ∉ S ∧ item ∈ Q
(LIRSCache. cache (assoc lruS item tick+) (assoc lruQ item tick+) tick+ limitS limitQ)
(let [k (apply min-key lruS (keys lruS))]
(if (contains? lruQ item)
; (2.2) item ∈ S ∧ item ∈ Q
(let [new-lruQ (-> lruQ (dissoc item) (assoc k tick+))]
(LIRSCache. cache
(-> lruS (dissoc k) (assoc item tick+) (prune-stack new-lruQ cache))
new-lruQ
tick+
limitS
limitQ))
; (2.1) item ∈ S ∧ item ∉ Q
(LIRSCache. cache
(-> lruS (assoc item tick+) (prune-stack lruQ cache))
lruQ
tick+
limitS
limitQ))))))
(miss [_ item result]
(let [tick+ (inc tick)]
(if (< (count cache) limitS)
; (1.1)
(let [k (apply min-key lruS (keys lruS))]
(LIRSCache. (assoc cache item result)
(-> lruS (dissoc k) (assoc item tick+))
lruQ
tick+
limitS
limitQ))
(let [k (apply min-key lruQ (keys lruQ))
new-lruQ (dissoc lruQ k)
new-cache (-> cache (dissoc k) (assoc item result))]
(if (contains? lruS item)
; (1.3)
(let [lastS (apply min-key lruS (keys lruS))]
(LIRSCache. new-cache
(-> lruS (dissoc lastS) (assoc item tick+) (prune-stack new-lruQ new-cache))
(assoc new-lruQ lastS tick+)
tick+
limitS
limitQ))
; (1.2)
(LIRSCache. new-cache
(assoc lruS item tick+)
(assoc new-lruQ item tick+)
tick+
limitS
limitQ))))))
(seed [_ base]
(LIRSCache. base
(into {} (for [x (range (- limitS) 0)] [x x]))
(into {} (for [x (range (- limitQ) 0)] [x x]))
0
limitS
limitQ))
Object
(toString [_]
(str cache \, \space lruS \, \space lruQ \, \space tick \, \space limitS \, \space limitQ)))
(defn clear-soft-cache! [^java.util.Map cache ^java.util.Map rcache ^ReferenceQueue rq]
(loop [r (.poll rq)]
(when r
(when-let [item (get rcache r)]
(.remove cache item))
(.remove rcache r)
(recur (.poll rq)))))
(defn make-reference [v rq]
(if (nil? v)
(SoftReference. ::nil rq)
(SoftReference. v rq)))
(defcache SoftCache [^java.util.Map cache ^java.util.Map rcache rq]
CacheProtocol
(lookup [_ item]
(when-let [^SoftReference r (get cache (or item ::nil))]
(let [v (.get r)]
(if (= ::nil v)
nil
v))))
(lookup [_ item not-found]
(if-let [^SoftReference r (get cache (or item ::nil))]
(if-let [v (.get r)]
(if (= ::nil v)
nil
v)
not-found)
not-found))
(has? [_ item]
(let [item (or item ::nil)
^SoftReference cell (get cache item)]
(boolean
(when cell
(not (nil? (.get cell)))))))
(hit [this item]
(clear-soft-cache! cache rcache rq)
this)
(miss [this item result]
(let [item (or item ::nil)
r (make-reference result rq)]
(.put cache item r)
(.put rcache r item)
(clear-soft-cache! cache rcache rq)
this))
(evict [this key]
(let [key (or key ::nil)
r (get cache key)]
(when r
(.remove cache key)
(.remove rcache r))
(clear-soft-cache! cache rcache rq)
this))
(seed [_ base]
(let [soft-cache? (instance? SoftCache base)
cache (ConcurrentHashMap.)
rcache (ConcurrentHashMap.)
rq (ReferenceQueue.)]
(if (seq base)
(doseq [[k ^SoftReference v] base]
(let [k (or k ::nil)
r (if soft-cache?
(make-reference (.get v) rq)
(make-reference v rq))]
(.put cache k r)
(.put rcache r k))))
(SoftCache. cache rcache rq)))
Object
(toString [_] (str cache)))
;; Factories
(defn basic-cache-factory
"Returns a pluggable basic cache initialied to `base`"
[base]
{:pre [(map? base)]}
(BasicCache. base))
(defn fifo-cache-factory
"Returns a FIFO cache with the cache and FIFO queue initialized to `base` --
the queue is filled as the values are pulled out of `base`. If the associative
structure can guarantee ordering, then the said ordering will define the
eventual eviction order. Otherwise, there are no guarantees for the eventual
eviction ordering.
This function takes an optional `:threshold` argument that defines the maximum number
of elements in the cache before the FIFO semantics apply (default is 32).
If the number of elements in `base` is greater than the limit then some items
in `base` will be dropped from the resulting cache. If the associative
structure used as `base` can guarantee sorting, then the last `limit` elements
will be used as the cache seed values. Otherwise, there are no guarantees about
the elements in the resulting cache."
[base & {threshold :threshold :or {threshold 32}}]
{:pre [(number? threshold) (< 0 threshold)
(map? base)]
:post [(== threshold (count (.q ^FIFOCache %)))]}
(clojure.core.cache/seed (FIFOCache. {} clojure.lang.PersistentQueue/EMPTY threshold) base))
(defn lru-cache-factory
"Returns an LRU cache with the cache and usage-table initialied to `base` --
each entry is initialized with the same usage value.
This function takes an optional `:threshold` argument that defines the maximum number
of elements in the cache before the LRU semantics apply (default is 32)."
[base & {threshold :threshold :or {threshold 32}}]
{:pre [(number? threshold) (< 0 threshold)
(map? base)]}
(clojure.core.cache/seed (LRUCache. {} (clojure.data.priority-map/priority-map) 0 threshold) base))
(defn ttl-cache-factory
"Returns a TTL cache with the cache and expiration-table initialized to `base` --
each with the same time-to-live.
This function also allows an optional `:ttl` argument that defines the default
time in milliseconds that entries are allowed to reside in the cache."
[base & {ttl :ttl :or {ttl 2000}}]
{:pre [(number? ttl) (<= 0 ttl)
(map? base)]}
(clojure.core.cache/seed (TTLCacheQ. {} {} clojure.lang.PersistentQueue/EMPTY 0 ttl) base))
(defn lu-cache-factory
"Returns an LU cache with the cache and usage-table initialied to `base`.
This function takes an optional `:threshold` argument that defines the maximum number
of elements in the cache before the LU semantics apply (default is 32)."
[base & {threshold :threshold :or {threshold 32}}]
{:pre [(number? threshold) (< 0 threshold)
(map? base)]}
(clojure.core.cache/seed (LUCache. {} (clojure.data.priority-map/priority-map) threshold) base))
(defn lirs-cache-factory
"Returns an LIRS cache with the S & R LRU lists set to the indicated
limits."
[base & {:keys [s-history-limit q-history-limit]
:or {s-history-limit 32
q-history-limit 32}}]
{:pre [(number? s-history-limit) (< 0 s-history-limit)
(number? q-history-limit) (< 0 q-history-limit)
(map? base)]}
(clojure.core.cache/seed (LIRSCache. {} {} {} 0 s-history-limit q-history-limit) base))
(defn soft-cache-factory
"Returns a SoftReference cache. Cached values will be referred to with
SoftReferences, allowing the values to be garbage collected when there is
memory pressure on the JVM.
SoftCache is a mutable cache, since it is always based on a
ConcurrentHashMap."
[base]
{:pre [(map? base)]}
(clojure.core.cache/seed (SoftCache. (ConcurrentHashMap.) (ConcurrentHashMap.) (ReferenceQueue.))
base))
core.cache-core.cache-1.0.207/src/main/clojure/clojure/core/cache/ 0000775 0000000 0000000 00000000000 13644155620 0024465 5 ustar 00root root 0000000 0000000 core.cache-core.cache-1.0.207/src/main/clojure/clojure/core/cache/wrapped.clj 0000664 0000000 0000000 00000017563 13644155620 0026635 0 ustar 00root root 0000000 0000000 ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.core.cache.wrapped
"A higher level way to use clojure.core.cache that assumes the immutable
cache is wrapped in an atom.
The API is (almost) the same as clojure.core.cache -- including the factory
functions -- but instead of accepting immutable caches, the functions
here accept atoms containing those caches. The factory functions return
new atoms containing the newly created cache.
In addition, lookup-or-miss provides a safe, atomic way to retrieve a
value from a cache or compute it if it is missing, without risking a
cache stampede."
(:require [clojure.core.cache :as c]))
(set! *warn-on-reflection* true)
(defn lookup
"Retrieve the value associated with `e` if it exists, else `nil` in
the 2-arg case. Retrieve the value associated with `e` if it exists,
else `not-found` in the 3-arg case.
Reads from the current version of the atom."
([cache-atom e]
(c/lookup @cache-atom e))
([cache-atom e not-found]
(c/lookup @cache-atom e not-found)))
(def ^{:private true} default-wrapper-fn #(%1 %2))
(defn lookup-or-miss
"Retrieve the value associated with `e` if it exists, else compute the
value (using value-fn, and optionally wrap-fn), update the cache for `e`
and then perform the lookup again.
value-fn (and wrap-fn) will only be called (at most) once even in the
case of retries, so there is no risk of cache stampede.
Since lookup can cause invalidation in some caches (such as TTL), we
trap that case and retry (a maximum of ten times)."
([cache-atom e value-fn]
(lookup-or-miss cache-atom e default-wrapper-fn value-fn))
([cache-atom e wrap-fn value-fn]
(let [d-new-value (delay (wrap-fn value-fn e))]
(loop [n 0
v (c/lookup (swap! cache-atom
c/through-cache
e
default-wrapper-fn
(fn [_] @d-new-value))
e
::expired)]
(when (< n 10)
(if (= ::expired v)
(recur (inc n)
(c/lookup (swap! cache-atom
c/through-cache
e
default-wrapper-fn
(fn [_] @d-new-value))
e
::expired))
v))))))
(defn has?
"Checks if the cache contains a value associated with `e`.
Reads from the current version of the atom."
[cache-atom e]
(c/has? @cache-atom e))
(defn hit
"Is meant to be called if the cache is determined to contain a value
associated with `e`.
Returns the updated cache from the atom. Provided for completeness."
[cache-atom e]
(swap! cache-atom c/hit e))
(defn miss
"Is meant to be called if the cache is determined to **not** contain a
value associated with `e`.
Returns the updated cache from the atom. Provided for completeness."
[cache-atom e ret]
(swap! cache-atom c/miss e ret))
(defn evict
"Removes an entry from the cache.
Returns the updated cache from the atom."
[cache-atom e]
(swap! cache-atom c/evict e))
(defn seed
"Is used to signal that the cache should be created with a seed.
The contract is that said cache should return an instance of its
own type.
Returns the updated cache from the atom. Provided for completeness."
[cache-atom base]
(swap! cache-atom c/seed base))
(defn through
"The basic hit/miss logic for the cache system. Expects a wrap function and
value function. The wrap function takes the value function and the item in question
and is expected to run the value function with the item whenever a cache
miss occurs. The intent is to hide any cache-specific cells from leaking
into the cache logic itelf."
([cache-atom item] (through default-wrapper-fn identity cache-atom item))
([value-fn cache-atom item] (through default-wrapper-fn value-fn cache-atom item))
([wrap-fn value-fn cache-atom item]
(swap! cache-atom c/through-cache item wrap-fn value-fn)))
(defn through-cache
"The basic hit/miss logic for the cache system. Like through but always has
the cache argument in the first position."
([cache-atom item] (through-cache cache-atom item default-wrapper-fn identity))
([cache-atom item value-fn] (through-cache cache-atom item default-wrapper-fn value-fn))
([cache-atom item wrap-fn value-fn]
(swap! cache-atom c/through-cache item wrap-fn value-fn)))
(defn basic-cache-factory
"Returns a pluggable basic cache initialied to `base`"
[base]
(atom (c/basic-cache-factory base)))
(defn fifo-cache-factory
"Returns a FIFO cache with the cache and FIFO queue initialized to `base` --
the queue is filled as the values are pulled out of `base`. If the associative
structure can guarantee ordering, then the said ordering will define the
eventual eviction order. Otherwise, there are no guarantees for the eventual
eviction ordering.
This function takes an optional `:threshold` argument that defines the maximum number
of elements in the cache before the FIFO semantics apply (default is 32).
If the number of elements in `base` is greater than the limit then some items
in `base` will be dropped from the resulting cache. If the associative
structure used as `base` can guarantee sorting, then the last `limit` elements
will be used as the cache seed values. Otherwise, there are no guarantees about
the elements in the resulting cache."
[base & {threshold :threshold :or {threshold 32}}]
(atom (c/fifo-cache-factory base :threshold threshold)))
(defn lru-cache-factory
"Returns an LRU cache with the cache and usage-table initialied to `base` --
each entry is initialized with the same usage value.
This function takes an optional `:threshold` argument that defines the maximum number
of elements in the cache before the LRU semantics apply (default is 32)."
[base & {threshold :threshold :or {threshold 32}}]
(atom (c/lru-cache-factory base :threshold threshold)))
(defn ttl-cache-factory
"Returns a TTL cache with the cache and expiration-table initialized to `base` --
each with the same time-to-live.
This function also allows an optional `:ttl` argument that defines the default
time in milliseconds that entries are allowed to reside in the cache."
[base & {ttl :ttl :or {ttl 2000}}]
(atom (c/ttl-cache-factory base :ttl ttl)))
(defn lu-cache-factory
"Returns an LU cache with the cache and usage-table initialied to `base`.
This function takes an optional `:threshold` argument that defines the maximum number
of elements in the cache before the LU semantics apply (default is 32)."
[base & {threshold :threshold :or {threshold 32}}]
(atom (c/lu-cache-factory base :threshold threshold)))
(defn lirs-cache-factory
"Returns an LIRS cache with the S & R LRU lists set to the indicated
limits."
[base & {:keys [s-history-limit q-history-limit]
:or {s-history-limit 32
q-history-limit 32}}]
(atom (c/lirs-cache-factory base
:s-history-limit s-history-limit
:q-history-limit q-history-limit)))
(defn soft-cache-factory
"Returns a SoftReference cache. Cached values will be referred to with
SoftReferences, allowing the values to be garbage collected when there is
memory pressure on the JVM.
SoftCache is a mutable cache, since it is always based on a
ConcurrentHashMap."
[base]
(atom (c/soft-cache-factory base)))
core.cache-core.cache-1.0.207/src/test/ 0000775 0000000 0000000 00000000000 13644155620 0017417 5 ustar 00root root 0000000 0000000 core.cache-core.cache-1.0.207/src/test/clojure/ 0000775 0000000 0000000 00000000000 13644155620 0021062 5 ustar 00root root 0000000 0000000 core.cache-core.cache-1.0.207/src/test/clojure/clojure/ 0000775 0000000 0000000 00000000000 13644155620 0022525 5 ustar 00root root 0000000 0000000 core.cache-core.cache-1.0.207/src/test/clojure/clojure/core/ 0000775 0000000 0000000 00000000000 13644155620 0023455 5 ustar 00root root 0000000 0000000 core.cache-core.cache-1.0.207/src/test/clojure/clojure/core/cache/ 0000775 0000000 0000000 00000000000 13644155620 0024520 5 ustar 00root root 0000000 0000000 core.cache-core.cache-1.0.207/src/test/clojure/clojure/core/cache/wrapped_test.clj 0000664 0000000 0000000 00000003360 13644155620 0027715 0 ustar 00root root 0000000 0000000 ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.core.cache.wrapped-test
(:require [clojure.core.cache.wrapped :as c]
[clojure.test :refer [deftest is]]))
(deftest basic-wrapped-test
(let [cache (c/basic-cache-factory {})]
(is (= nil (c/lookup cache :a)))
(is (= ::missing (c/lookup cache :a ::missing)))
;; mutating operation
(is (= 42 (c/lookup-or-miss cache :a (constantly 42))))
;; cache now contains :a
(is (= 42 (c/lookup cache :a)))
;; :a is present, does not call value-fn
(is (= 42 (c/lookup-or-miss cache :a #(throw (ex-info "bad" {:key %})))))
;; cache still contains :a as 42
(is (= 42 (c/lookup cache :a)))
(c/evict cache :a)
(is (= nil (c/lookup cache :a)))
(is (= ::missing (c/lookup cache :a ::missing)))))
(deftest wrapped-ttl-test
;; TTL lookup-or-miss can expire on the lookup so this test verifies
;; that bug (in 0.8.0) so I can fix it in 0.8.1!
(let [cache (c/ttl-cache-factory {} :ttl 1)
limit 2000000
start (System/currentTimeMillis)]
(loop [n 0]
(if-not (c/lookup-or-miss cache :a (constantly 42))
(do
(is false (str "Failure on call " n)))
(if (< n limit)
(recur (+ 1 n)))))
(println "ttl test completed" limit "calls in"
(- (System/currentTimeMillis) start) "ms")))
core.cache-core.cache-1.0.207/src/test/clojure/clojure/core/cache_test.clj 0000664 0000000 0000000 00000052636 13644155620 0026265 0 ustar 00root root 0000000 0000000 ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns ^{:doc "A caching library for Clojure."
:author "Fogus"}
clojure.core.cache-test
(:use [clojure.core.cache] :reload-all)
(:use [clojure.test])
(:import (clojure.core.cache BasicCache FIFOCache LRUCache TTLCacheQ LUCache
LIRSCache)
(java.lang.ref ReferenceQueue SoftReference)
(java.util.concurrent ConcurrentHashMap)))
(println "\nTesting with Clojure" (clojure-version))
(deftest test-basic-cache-lookup
(testing "that the BasicCache can lookup as expected"
(is (= :robot (lookup (miss (BasicCache. {}) '(servo) :robot) '(servo))))))
(defn do-dot-lookup-tests [c]
(are [expect actual] (= expect actual)
1 (.lookup c :a)
2 (.lookup c :b)
42 (.lookup c :c 42)
nil (.lookup c :c)))
(defn do-ilookup-tests [c]
(are [expect actual] (= expect actual)
1 (:a c)
2 (:b c)
42 (:X c 42)
nil (:X c)))
(defn do-assoc [c]
(are [expect actual] (= expect actual)
1 (:a (assoc c :a 1))
nil (:a (assoc c :b 1))))
(defn do-dissoc [c]
(are [expect actual] (= expect actual)
2 (:b (dissoc c :a))
nil (:a (dissoc c :a))
nil (:b (-> c (dissoc :a) (dissoc :b)))
0 (count (-> c (dissoc :a) (dissoc :b)))))
(defn do-getting [c]
(are [actual expect] (= expect actual)
(get c :a) 1
(get c :e) nil
(get c :e 0) 0
(get c :b 0) 2
(get c :f 0) nil
(get-in c [:c :e]) 4
(get-in c '(:c :e)) 4
(get-in c [:c :x]) nil
(get-in c [:f]) nil
(get-in c [:g]) false
(get-in c [:h]) nil
(get-in c []) c
(get-in c nil) c
(get-in c [:c :e] 0) 4
(get-in c '(:c :e) 0) 4
(get-in c [:c :x] 0) 0
(get-in c [:b] 0) 2
(get-in c [:f] 0) nil
(get-in c [:g] 0) false
(get-in c [:h] 0) 0
(get-in c [:x :y] {:y 1}) {:y 1}
(get-in c [] 0) c
(get-in c nil 0) c))
(defn do-finding [c]
(are [expect actual] (= expect actual)
(find c :a) [:a 1]
(find c :b) [:b 2]
(find c :c) nil
(find c nil) nil))
(defn do-contains [c]
(are [expect actual] (= expect actual)
(contains? c :a) true
(contains? c :b) true
(contains? c :c) false
(contains? c nil) false))
(def big-map {:a 1, :b 2, :c {:d 3, :e 4}, :f nil, :g false, nil {:h 5}})
(def small-map {:a 1 :b 2})
(deftest test-basic-cache-ilookup
(testing "counts"
(is (= 0 (count (BasicCache. {}))))
(is (= 1 (count (BasicCache. {:a 1})))))
(testing "that the BasicCache can lookup via keywords"
(do-ilookup-tests (BasicCache. small-map)))
(testing "that the BasicCache can .lookup"
(do-dot-lookup-tests (BasicCache. small-map)))
(testing "assoc and dissoc for BasicCache"
(do-assoc (BasicCache. {}))
(do-dissoc (BasicCache. {:a 1 :b 2})))
(testing "that get and cascading gets work for BasicCache"
(do-getting (BasicCache. big-map)))
(testing "that finding works for BasicCache"
(do-finding (BasicCache. small-map)))
(testing "that contains? works for BasicCache"
(do-contains (BasicCache. small-map))))
(deftest test-fifo-cache-ilookup
(testing "that the FifoCache can lookup via keywords"
(do-ilookup-tests (FIFOCache. small-map clojure.lang.PersistentQueue/EMPTY 2)))
(testing "that the FifoCache can lookup via keywords"
(do-dot-lookup-tests (FIFOCache. small-map clojure.lang.PersistentQueue/EMPTY 2)))
(testing "assoc and dissoc for FifoCache"
(do-assoc (FIFOCache. {} clojure.lang.PersistentQueue/EMPTY 2))
(do-dissoc (FIFOCache. {:a 1 :b 2} clojure.lang.PersistentQueue/EMPTY 2)))
(testing "that get and cascading gets work for FifoCache"
(do-getting (FIFOCache. big-map clojure.lang.PersistentQueue/EMPTY 2)))
(testing "that finding works for FifoCache"
(do-finding (FIFOCache. small-map clojure.lang.PersistentQueue/EMPTY 2)))
(testing "that contains? works for FifoCache"
(do-contains (FIFOCache. small-map clojure.lang.PersistentQueue/EMPTY 2)))
(testing "that FIFO caches starting with less elements than the threshold work"
(let [C (fifo-cache-factory (sorted-map :a 1, :b 2) :threshold 3)]
(are [x y] (= x y)
{:a 1, :b 2, :c 3} (.cache (assoc C :c 3))
{:d 4, :b 2, :c 3} (.cache (assoc C :c 3 :d 4))))))
(deftest test-lru-cache-ilookup
(testing "that the LRUCache can lookup via keywords"
(do-ilookup-tests (LRUCache. small-map {} 0 2)))
(testing "that the LRUCache can lookup via keywords"
(do-dot-lookup-tests (LRUCache. small-map {} 0 2)))
(testing "assoc and dissoc for LRUCache"
(do-assoc (LRUCache. {} {} 0 2))
(do-dissoc (LRUCache. {:a 1 :b 2} {} 0 2)))
(testing "that get and cascading gets work for LRUCache"
(do-getting (LRUCache. big-map {} 0 2)))
(testing "that finding works for LRUCache"
(do-finding (LRUCache. small-map {} 0 2)))
(testing "that contains? works for LRUCache"
(do-contains (LRUCache. small-map {} 0 2))))
(deftest test-lru-cache
(testing "LRU-ness with empty cache and threshold 2"
(let [C (lru-cache-factory {} :threshold 2)]
(are [x y] (= x y)
{:a 1, :b 2} (-> C (assoc :a 1) (assoc :b 2) .cache)
{:b 2, :c 3} (-> C (assoc :a 1) (assoc :b 2) (assoc :c 3) .cache)
{:a 1, :c 3} (-> C (assoc :a 1) (assoc :b 2) (.hit :a) (assoc :c 3) .cache))))
(testing "LRU-ness with seeded cache and threshold 4"
(let [C (lru-cache-factory {:a 1, :b 2} :threshold 4)]
(are [x y] (= x y)
{:a 1, :b 2, :c 3, :d 4} (-> C (assoc :c 3) (assoc :d 4) .cache)
{:a 1, :c 3, :d 4, :e 5} (-> C (assoc :c 3) (assoc :d 4) (.hit :c) (.hit :a) (assoc :e 5) .cache))))
(testing "regressions against LRU eviction before threshold met"
(is (= {:b 3 :a 4}
(-> (clojure.core.cache/lru-cache-factory {} :threshold 2)
(assoc :a 1)
(assoc :b 2)
(assoc :b 3)
(assoc :a 4)
.cache)))
(is (= {:e 6, :d 5, :c 4}
(-> (clojure.core.cache/lru-cache-factory {} :threshold 3)
(assoc :a 1)
(assoc :b 2)
(assoc :b 3)
(assoc :c 4)
(assoc :d 5)
(assoc :e 6)
.cache)))
(is (= {:a 1 :b 3}
(-> (clojure.core.cache/lru-cache-factory {} :threshold 2)
(assoc :a 1)
(assoc :b 2)
(assoc :b 3)
.cache))))
(is (= {:d 4 :e 5}
(-> (lru-cache-factory {} :threshold 2)
(hit :x)
(hit :y)
(hit :z)
(assoc :a 1)
(assoc :b 2)
(assoc :c 3)
(assoc :d 4)
(assoc :e 5)
.cache))))
(defn sleepy [e t] (Thread/sleep t) e)
(deftest test-ttl-cache-ilookup
(let [five-secs (+ 5000 (System/currentTimeMillis))
big-time (into {} (for [[k _] big-map] [k [0 five-secs]]))
big-q (into clojure.lang.PersistentQueue/EMPTY
(for [[k _] big-map] [k 0 five-secs]))
small-time (into {} (for [[k _] small-map] [k [0 five-secs]]))
small-q (into clojure.lang.PersistentQueue/EMPTY
(for [[k _] small-map] [k 0 five-secs]))]
(testing "that the TTLCacheQ can lookup via keywords"
(do-ilookup-tests (TTLCacheQ. small-map small-time small-q 1 2000)))
(testing "that the TTLCacheQ can lookup via keywords"
(do-dot-lookup-tests (TTLCacheQ. small-map small-time small-q 1 2000)))
(testing "assoc and dissocQ for TTLCacheQ"
(do-assoc (TTLCacheQ. {} {} clojure.lang.PersistentQueue/EMPTY 1 2000))
(do-dissoc (TTLCacheQ. {:a 1 :b 2}
{:a [0 five-secs] :b [0 five-secs]}
(into clojure.lang.PersistentQueue/EMPTY
[[:a 0 five-secs] [:b 0 five-secs]])
1
2000)))
(testing "that get and cascading gets work for TTLCacheQ"
(do-getting (TTLCacheQ. big-map big-time big-q 1 2000)))
(testing "that finding works for TTLCacheQ"
(do-finding (TTLCacheQ. small-map small-time small-q 1 2000)))
(testing "that contains? works for TTLCacheQ"
(do-contains (TTLCacheQ. small-map small-time small-q 1 2000)))))
(defn- ttl-q-check
[start nap [k g t]]
[k g (<= start (+ start nap) t (+ start nap 100))])
(deftest test-ttl-cache
(testing "TTL-ness with empty cache"
(let [start (System/currentTimeMillis)
C (ttl-cache-factory {} :ttl 500)
C' (-> C (assoc :a 1) (assoc :b 2))]
(are [x y] (= x y)
[[:a 1 true], [:b 2 true]] (map (partial ttl-q-check start 0) (.q C'))
{:a 1, :b 2} (.cache C')
3 (.gen C')))
(let [start (System/currentTimeMillis)
C (ttl-cache-factory {} :ttl 500)
C' (-> C (assoc :a 1) (assoc :b 2) (sleepy 700) (assoc :c 3))]
(are [x y] (= x y)
[[:c 3 true]] (map (partial ttl-q-check start 700) (.q C'))
{:c 3} (.cache C')
4 (.gen C'))))
(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))))))
(testing "TTL cache does not contain a value that was removed from underlying cache."
(let [underlying-cache (lru-cache-factory {} :threshold 1)
C (ttl-cache-factory underlying-cache :ttl 360000)]
(is (not (-> C (assoc :a 1) (assoc :b 2) (has? :a)))))))
(deftest test-lu-cache-ilookup
(testing "that the LUCache can lookup via keywords"
(do-ilookup-tests (LUCache. small-map {} 2)))
(testing "that the LUCache can lookup via keywords"
(do-dot-lookup-tests (LUCache. small-map {} 2)))
(testing "assoc and dissoc for LUCache"
(do-assoc (LUCache. {} {} 2))
(do-dissoc (LUCache. {:a 1 :b 2} {} 2))))
(deftest test-lu-cache
(testing "LU-ness with empty cache"
(let [C (lu-cache-factory {} :threshold 2)]
(are [x y] (= x y)
{:a 1, :b 2} (-> C (assoc :a 1) (assoc :b 2) .cache)
{:b 2, :c 3} (-> C (assoc :a 1) (assoc :b 2) (.hit :b) (assoc :c 3) .cache)
{:b 2, :c 3} (-> C (assoc :a 1) (assoc :b 2) (.hit :b) (.hit :b) (.hit :a) (assoc :c 3) .cache))))
(testing "LU-ness with seeded cache"
(let [C (lu-cache-factory {:a 1, :b 2} :threshold 4)]
(are [x y] (= x y)
{:a 1, :b 2, :c 3, :d 4} (-> C (assoc :c 3) (assoc :d 4) .cache)
{:a 1, :c 3, :d 4, :e 5} (-> C (assoc :c 3) (assoc :d 4) (.hit :a) (assoc :e 5) .cache)
{:b 2, :c 3, :d 4, :e 5} (-> C (assoc :c 3) (assoc :d 4) (.hit :b) (.hit :c) (.hit :d) (assoc :e 5) .cache))))
(testing "regressions against LRU eviction before threshold met"
(is (= (-> (clojure.core.cache/lu-cache-factory {} :threshold 2)
(assoc :a 1)
(assoc :b 2)
(assoc :b 3)
(assoc :a 4))
{:b 3 :a 4}))
(is (= (-> (clojure.core.cache/lu-cache-factory {} :threshold 3)
(assoc :a 1)
(assoc :b 2)
(assoc :b 3)
(assoc :c 4)
(assoc :d -5)
;; ensure that the test result does not rely on
;; arbitrary tie-breakers in number of hits
(assoc :d 5)
(assoc :e 6))
{: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
(defn- lirs-map [lirs]
{:cache (.cache lirs)
:lruS (.lruS lirs)
:lruQ (.lruQ lirs)
:tick (.tick lirs)
:limitS (.limitS lirs)
:limitQ (.limitQ lirs)})
(deftest test-LIRSCache
(testing "that the LIRSCache can lookup as expected"
(is (= :robot (lookup (miss (seed (LIRSCache. {} {} {} 0 1 1) {}) '(servo) :robot) '(servo)))))
(testing "a hit of a LIR block:
L LIR block
H HIR block
N non-resident HIR block
+-----------------------------+ +----------------+
| HIT 4 | | HIT 8 |
| v | |
| | |
H 5 | L 4 | v
H 3 | H 5 |
N 2 | H 3 | L 8
L 1 | N 2 | L 4
N 6 | L 1 | H 5
N 9 | N 6 | H 3
L 4---+ 5 N 9 | 5 N 2 5
L 8 3 L 8---+ 3 L 1 3
S Q S Q S Q
"
(let [lirs (LIRSCache. {:1 1 :3 3 :4 4 :5 5 :8 8}
{:5 7 :3 6 :2 5 :1 4 :6 3 :9 2 :4 1 :8 0}
{:5 1 :3 0} 7 3 2)]
(testing "hit 4"
(is (= (lirs-map (hit lirs :4))
(lirs-map (LIRSCache. {:1 1 :3 3 :4 4 :5 5 :8 8}
{:5 7 :3 6 :2 5 :1 4 :6 3 :9 2 :4 8 :8 0}
{:5 1 :3 0} 8 3 2)))))
(testing "hit 8 prunes the stack"
(is (= (lirs-map (-> lirs (hit :4) (hit :8)))
(lirs-map (LIRSCache. {:1 1 :3 3 :4 4 :5 5 :8 8}
{:5 7 :3 6 :2 5 :1 4 :4 8 :8 9}
{:5 1 :3 0} 9 3 2)))))))
(testing "a hit of a HIR block:
L LIR block
H HIR block
N non-resident HIR block
HIT 3 HIT 5
+-----------------------------+ +------------------+-----+
| | | | |
L 4 |+----------------------------+-----+ | v |
L 8 || v | | |
H 5 || v | H 5 v
H 3-- | L 3 | L 3
N 2 | 5 L 4 1 | L 4 5
L 1---+ 3 L 8 5---+ L 8 1
S Q S Q S Q
"
(let [lirs (LIRSCache. {:1 1 :3 3 :4 4 :5 5 :8 8}
{:4 9 :8 8 :5 7 :3 6 :2 5 :1 4}
{:5 1 :3 0} 9 3 2)]
(testing "hit 3 prunes the stack and moves oldest block of lruS to lruQ"
(is (= (lirs-map (hit lirs :3))
{:cache {:1 1 :3 3 :4 4 :5 5 :8 8}
:lruS {:3 10 :4 9 :8 8}
:lruQ {:1 10 :5 1}
:tick 10 :limitS 3 :limitQ 2})))
(testing "hit 5 adds the block to lruS"
(is (= (lirs-map (-> lirs (hit :3) (hit :5)))
{:cache {:1 1 :3 3 :4 4 :5 5 :8 8}
:lruS {:5 11 :3 10 :4 9 :8 8}
:lruQ {:5 11 :1 10}
:tick 11 :limitS 3 :limitQ 2})))))
(testing "a miss:
L LIR block
H HIR block
N non-resident HIR block
MISS 7 MISS 9 MISS 5
---------------------+-----+ -----------------+-----+ +-------------------+
| | v | | |
v | | | v
| H 9 + -| - - +
H 7 | H 7 | | L 5 +--+
H 5 H 5 v N 5- + v H 9 | v
L 3 L 3 L 3 N 7 |
L 4 5 L 4 7 L 4 9 L 3 | 8
L 8 1 L 8 5 L 8--+ 7 L 4 | 9
+-------------------------------+
S Q S Q S Q S Q
"
(let [lirs (LIRSCache. {:1 1 :3 3 :4 4 :5 5 :8 8}
{:5 11 :3 10 :4 9 :8 8}
{:5 11 :1 10} 11 3 2)]
(testing "miss 7 adds the block to lruS and lruQ and removes the oldest block in lruQ"
(is (= (lirs-map (miss lirs :7 7))
{:cache {:3 3 :4 4 :5 5 :8 8 :7 7}
:lruS {:7 12 :5 11 :3 10 :4 9 :8 8}
:lruQ {:7 12 :5 11}
:tick 12 :limitS 3 :limitQ 2})))
(testing "miss 9 makes 5 a non-resident HIR block"
(is (= (lirs-map (-> lirs (miss :7 7) (miss :9 9)))
{:cache {:3 3 :4 4 :8 8 :7 7 :9 9}
:lruS {:9 13 :7 12 :5 11 :3 10 :4 9 :8 8}
:lruQ {:9 13 :7 12}
:tick 13 :limitS 3 :limitQ 2})))
(testing "miss 5, a non-resident HIR block becomes a new LIR block"
(is (= (lirs-map (-> lirs (miss :7 7) (miss :9 9) (miss :5 5)))
{:cache {:3 3 :4 4 :8 8 :9 9 :5 5}
:lruS {:5 14 :9 13 :7 12 :3 10 :4 9}
:lruQ {:8 14 :9 13}
:tick 14 :limitS 3 :limitQ 2}))))))
(deftest test-soft-cache-ilookup
(testing "counts"
(is (= 0 (count (soft-cache-factory {}))))
(is (= 1 (count (soft-cache-factory {:a 1})))))
(testing "that the SoftCache can lookup via keywords"
(do-ilookup-tests (soft-cache-factory small-map)))
(testing "that the SoftCache can .lookup"
(do-dot-lookup-tests (soft-cache-factory small-map)))
(testing "that get and cascading gets work for SoftCache"
(do-getting (soft-cache-factory big-map)))
(testing "that finding works for SoftCache"
(do-finding (soft-cache-factory small-map)))
(testing "that contains? works for SoftCache"
(do-contains (soft-cache-factory small-map))))
(deftest test-clear-soft-cache!
(let [rq (ReferenceQueue.)
ref (SoftReference. :bar rq)
cache (doto (ConcurrentHashMap.)
(.put :foo ref))
rcache (doto (ConcurrentHashMap.)
(.put ref :foo))
_ (clear-soft-cache! cache rcache rq)]
(is (contains? cache :foo) (str cache))
(is (contains? rcache ref) (str rcache))
(.clear ref)
(.enqueue ref)
(is (not (.get ref)))
(let [_ (clear-soft-cache! cache rcache rq)]
(is (not (contains? cache :foo)))
(is (not (contains? rcache ref))))))
(deftest test-soft-cache
(let [ref (atom nil)
old-make-reference make-reference]
(with-redefs [make-reference (fn [& args]
(reset! ref (apply old-make-reference args))
@ref)]
(let [old-soft-cache (soft-cache-factory {:foo1 :bar})
r @ref
soft-cache (assoc old-soft-cache :foo2 :baz)]
(is (and r (= :bar (.get r))))
(.clear r)
(.enqueue r)
(is (nil? (.lookup soft-cache :foo1)))
(is (nil? (.lookup old-soft-cache :foo1)))
(is (= :quux (.lookup soft-cache :foo1 :quux)))
(is (= :quux (.lookup old-soft-cache :foo1 :quux)))
(is (= :quux (.lookup soft-cache :foo3 :quux)))
(is (= :quux (.lookup old-soft-cache :foo3 :quux)))
(is (not (.has? soft-cache :foo1)))
(is (not (.has? old-soft-cache :foo1)))))))
(deftest test-soft-cache-eviction-handling
(let [ref (atom nil)
old-make-reference make-reference]
(with-redefs [make-reference (fn [& args]
(reset! ref (apply old-make-reference args))
@ref)]
(let [cache (soft-cache-factory {})]
(miss cache :foo "foo")
(.enqueue @ref)
(evict cache :foo)))))
(deftest test-equiv
(is (= (fifo-cache-factory {:a 1 :c 3} :threshold 3)
(fifo-cache-factory {:a 1 :c 3} :threshold 3))))
(deftest test-persistent-cons
(is (let [starts-with-a (fifo-cache-factory {:a 1} :threshold 3)]
(= (fifo-cache-factory {:a 1 :c 3} :threshold 3)
(conj starts-with-a [:c 3])
(conj starts-with-a {:c 3})))))
(deftest evict-with-object-exception
(let [thing (proxy [Object] []
(equals [obj] (throw (new Exception "Boom!"))))]
(are [x y] (= x y)
{:b 2} (-> (lru-cache-factory {:a thing, :b 2}) (evict :a) (.cache))
{:b 2} (-> (lu-cache-factory {:a thing, :b 2}) (evict :a) (.cache))
{:b 2} (-> (fifo-cache-factory {:a thing, :b 2}) (evict :a) (.cache)))))
(deftest test-cache-iterable
(let [c (fifo-cache-factory {:a 1 :b 2} :threshold 10)]
(is (= #{:a :b} (set (iterator-seq (.iterator (keys c))))))))
(deftest test-fifo-miss-does-not-drop-ccache-39
(let [c (fifo-cache-factory {:a 1 :b 2} :threshold 2)]
(is (= #{:a :c} (set (-> c (evict :b) (miss :c 42) (.q)))))
(is (= #{:c :d} (set (-> c (evict :b) (miss :c 42) (miss :d 43) (.q)))))))