├── doc └── intro.md ├── .gitignore ├── deps.edn ├── CONTRIBUTING.md ├── src ├── main │ ├── dotnet │ │ └── packager │ │ │ ├── clojure.core.cache.sln │ │ │ └── clojure.core.cache.csproj │ └── clojure │ │ └── clojure │ │ └── core │ │ ├── cache │ │ └── wrapped.clj │ │ └── cache.clj └── test │ └── clojure │ └── clojure │ └── core │ ├── cache │ └── wrapped_test.clj │ └── cache_test.clj ├── README.md ├── project.clj ├── LICENSE └── epl.html /doc/intro.md: -------------------------------------------------------------------------------- 1 | # Introduction to clr.core.cache 2 | 3 | TODO: write [great documentation](http://jacobian.org/writing/great-documentation/what-to-write/) 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /lib 3 | /classes 4 | /checkouts 5 | pom.xml 6 | *.jar 7 | *.class 8 | *.dll 9 | *.pdb 10 | *.exe 11 | .lein-deps-sum 12 | .lein-failures 13 | .lein-plugins 14 | .cpcache 15 | 16 | #Visual Studio artifacts 17 | bin/ 18 | obj/ 19 | .vs/ 20 | *.user 21 | *.suo 22 | *.nupkg -------------------------------------------------------------------------------- /deps.edn: -------------------------------------------------------------------------------- 1 | {:paths ["src/main/clojure"] 2 | :deps 3 | {io.github.clojure/clr.data.priority-map {:git/tag "v1.2.0" :git/sha "1c22751"}} 4 | 5 | :aliases 6 | {:test 7 | {:extra-paths ["src/test/clojure"] 8 | :extra-deps {io.github.dmiller/test-runner {:git/sha "c055ea13d19c6a9b9632aa2370fcc2215c8043c3"}} 9 | ;; :main-opts ["-m" "cognitect.test-runner" "-d" "src/test/clojure"] 10 | :exec-fn cognitect.test-runner.api/test 11 | :exec-args {:dirs ["src/test/clojure"]}}}} -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | This is a [Clojure contrib] project. 2 | 3 | Under the Clojure contrib [guidelines], this project cannot accept 4 | pull requests. All patches must be submitted via [JIRA]. 5 | 6 | See [Contributing] on the Clojure website for 7 | more information on how to contribute. 8 | 9 | [Clojure contrib]: https://clojure.org/community/contrib_libs 10 | [Contributing]: https://clojure.org/community/contributing 11 | [JIRA]: https://clojure.atlassian.net/browse/TANAL 12 | [guidelines]: https://clojure.org/community/contrib_howto -------------------------------------------------------------------------------- /src/main/dotnet/packager/clojure.core.cache.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.4.33103.184 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "clojure.core.cache", "clojure.core.cache.csproj", "{A56D29F8-5610-42FB-815F-B9BDB501A1FD}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {A56D29F8-5610-42FB-815F-B9BDB501A1FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {A56D29F8-5610-42FB-815F-B9BDB501A1FD}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {A56D29F8-5610-42FB-815F-B9BDB501A1FD}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {A56D29F8-5610-42FB-815F-B9BDB501A1FD}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {4E1AE273-CF91-4ACF-AE54-1D8C4E58E2DE} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /src/main/dotnet/packager/clojure.core.cache.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;netstandard2.1 5 | 6 | 7 | 8 | clojure.core.cache 9 | clojure.core 10 | clojure.core.cache 11 | clojure.core.cache 12 | clojure.core.cache 13 | David Miller 14 | Port of the core.cache library to ClojureCLR 15 | Copyright © Rich Hickey, ClojureCLR contributors 16 | EPL-1.0 17 | https://github.com/clojure/clr.core.cache 18 | ClojureCLR contributors 19 | Clojure;ClojureCLR 20 | 1.1.234 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # clr.core.cache 2 | 3 | A port of [clojure/core.cache](https://github.com/clojure/core.cache) library to ClojureCLR. 4 | 5 | See that site for documentation. 6 | 7 | ## Releases 8 | 9 | 10 | The latest stable release is 1.2.0. 11 | 12 | [CLI/`deps.edn`](https://clojure.org/reference/deps_edn) dependency information: 13 | ```clojure 14 | {io.github.clojure/clr.core.cache {:git/tag "v1.1.234" :git/sha "56e4406"}} 15 | ``` 16 | 17 | Nuget reference: 18 | 19 | ``` 20 | PM> Install-Package clojure.core.cache -Version 1.1.234 21 | ``` 22 | 23 | Leiningen/Clojars reference: 24 | 25 | ``` 26 | [org.clojure.clr/core.cache "1.1.234"] 27 | ``` 28 | 29 | ## License 30 | 31 | 32 | Copyright (C) 2024 Rich Hickey & ClojureCLR contributors 33 | Distributed under the Eclipse Public License, the same as Clojure. 34 | 35 | The parent project has this: 36 | 37 | C> opyright (c) Rich Hickey, Michael Fogus and contributors, 2012-2023. 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 bythe terms of this license. You must not remove this notice, or any other, from this software. -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject org.clojure.clr/core.cache "1.1.234" 2 | :description "A port of core.cache to ClojureCLR" 3 | :url "https://github.com/clojure/clr.core.cache" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[org.clojure.clr/data.priority-map "1.2.0"]] 7 | :warn-on-reflection true 8 | :source-paths ["src/main/clojure"] 9 | :test-paths ["src/test/clojure"] 10 | :deploy-repositories [["clojars" {:url "https://clojars.org/repo/" 11 | :sign-releases false}]] 12 | :min-lein-version "2.0.0" 13 | :plugins [[lein-clr "0.2.1"]] 14 | :clr {:cmd-templates {:clj-exe [[?PATH "mono"] [CLJCLR14_40 %1]] 15 | :clj-dep [[?PATH "mono"] ["target/clr/clj/Debug 4.0" %1]] 16 | :clj-url "http://sourceforge.net/projects/clojureclr/files/clojure-clr-1.4.1-Debug-4.0.zip/download" 17 | :clj-zip "clojure-clr-1.4.1-Debug-4.0.zip" 18 | :curl ["curl" "--insecure" "-f" "-L" "-o" %1 %2] 19 | :nuget-ver [[?PATH "mono"] [*PATH "nuget.exe"] "install" %1 "-Version" %2] 20 | :nuget-any [[?PATH "mono"] [*PATH "nuget.exe"] "install" %1] 21 | :unzip ["unzip" "-d" %1 %2] 22 | :wget ["wget" "--no-check-certificate" "--no-clobber" "-O" %1 %2]} 23 | ;; for automatic download/unzip of ClojureCLR, 24 | ;; 1. make sure you have curl or wget installed and on PATH, 25 | ;; 2. uncomment deps in :deps-cmds, and 26 | ;; 3. use :clj-dep instead of :clj-exe in :main-cmd and :compile-cmd 27 | :deps-cmds [; [:wget :clj-zip :clj-url] ; edit to use :curl instead of :wget 28 | ; [:unzip "../clj" :clj-zip] 29 | ] 30 | :main-cmd [:clj-exe "Clojure.Main.exe"] 31 | :compile-cmd [:clj-exe "Clojure.Compile.exe"]}) 32 | -------------------------------------------------------------------------------- /src/test/clojure/clojure/core/cache/wrapped_test.clj: -------------------------------------------------------------------------------- 1 | ; Copyright (c) Rich Hickey. All rights reserved. 2 | ; The use and distribution terms for this software are covered by the 3 | ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) 4 | ; which can be found in the file epl-v10.html at the root of this distribution. 5 | ; By using this software in any fashion, you are agreeing to be bound by 6 | ; the terms of this license. 7 | ; You must not remove this notice, or any other, from this software. 8 | 9 | (ns clojure.core.cache.wrapped-test 10 | (:require [clojure.core.cache.wrapped :as c] 11 | [clojure.core.cache :as cache] 12 | [clojure.test :refer [deftest is]])) 13 | 14 | (deftest basic-wrapped-test 15 | (let [cache (c/basic-cache-factory {})] 16 | (is (= nil (c/lookup cache :a))) 17 | (is (= ::missing (c/lookup cache :a ::missing))) 18 | ;; mutating operation 19 | (is (= 42 (c/lookup-or-miss cache :a (constantly 42)))) 20 | ;; cache now contains :a 21 | (is (= 42 (c/lookup cache :a))) 22 | ;; :a is present, does not call value-fn 23 | (is (= 42 (c/lookup-or-miss cache :a #(throw (ex-info "bad" {:key %}))))) 24 | ;; cache still contains :a as 42 25 | (is (= 42 (c/lookup cache :a))) 26 | (c/evict cache :a) 27 | (is (= nil (c/lookup cache :a))) 28 | (is (= ::missing (c/lookup cache :a ::missing))))) 29 | 30 | (deftest wrapped-ttl-test 31 | ;; TTL lookup-or-miss can expire on the lookup so this test verifies 32 | ;; that bug (in 0.8.0) so I can fix it in 0.8.1! 33 | (let [cache (c/ttl-cache-factory {} :ttl 1) 34 | limit 2000000 35 | start (Environment/TickCount)] ;;; System/currentTimeMillis 36 | (loop [n 0] 37 | (if-not (c/lookup-or-miss cache :a (constantly 42)) 38 | (do 39 | (is false (str "Failure on call " n))) 40 | (if (< n limit) 41 | (recur (+ 1 n))))) 42 | (println "ttl test completed" limit "calls in" 43 | (- (Environment/TickCount) start) "ms"))) ;;; System/currentTimeMillis 44 | 45 | (deftest cache-stampede 46 | (let [thread-count 100 47 | cache-atom (-> {} 48 | (cache/ttl-cache-factory :ttl 120000) 49 | (cache/lu-cache-factory :threshold 100) 50 | (atom)) 51 | latch (System.Threading.CountdownEvent. thread-count) ;;; java.util.concurrent.CountDownLatch. 52 | invocations-counter (atom 0) 53 | values (atom [])] 54 | ;;; (dotimes [_ thread-count] 55 | ;;; (.start (Thread. (fn [] 56 | ;;; (swap! values conj 57 | ;;; (c/lookup-or-miss cache-atom "my-key" 58 | ;;; (fn [_] 59 | ;;; (swap! invocations-counter inc) 60 | ;;; (Thread/sleep 3000) 61 | ;;; "some value"))) 62 | ;;; (.countDown latch))))) 63 | (dotimes [_ thread-count] 64 | (.Start (System.Threading.Thread. 65 | (gen-delegate System.Threading.ThreadStart [] 66 | (swap! values conj 67 | (c/lookup-or-miss cache-atom "my-key" 68 | (fn [_] 69 | (swap! invocations-counter inc) 70 | (System.Threading.Thread/Sleep 3000) 71 | "some value"))) 72 | (.Signal latch))))) 73 | ;;; (.await latch) 74 | (.Wait latch) 75 | (is (= 1 (deref invocations-counter))) 76 | (doseq [v @values] 77 | (is (= "some value" v))))) -------------------------------------------------------------------------------- /src/main/clojure/clojure/core/cache/wrapped.clj: -------------------------------------------------------------------------------- 1 | ; Copyright (c) Rich Hickey. All rights reserved. 2 | ; The use and distribution terms for this software are covered by the 3 | ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) 4 | ; which can be found in the file epl-v10.html at the root of this distribution. 5 | ; By using this software in any fashion, you are agreeing to be bound by 6 | ; the terms of this license. 7 | ; You must not remove this notice, or any other, from this software. 8 | 9 | (ns clojure.core.cache.wrapped 10 | "A higher level way to use clojure.core.cache that assumes the immutable 11 | cache is wrapped in an atom. 12 | 13 | The API is (almost) the same as clojure.core.cache -- including the factory 14 | functions -- but instead of accepting immutable caches, the functions 15 | here accept atoms containing those caches. The factory functions return 16 | new atoms containing the newly created cache. 17 | 18 | In addition, lookup-or-miss provides a safe, atomic way to retrieve a 19 | value from a cache or compute it if it is missing, without risking a 20 | cache stampede." 21 | (:require [clojure.core.cache :as c])) 22 | 23 | (set! *warn-on-reflection* true) 24 | 25 | (defn lookup 26 | "Retrieve the value associated with `e` if it exists, else `nil` in 27 | the 2-arg case. Retrieve the value associated with `e` if it exists, 28 | else `not-found` in the 3-arg case. 29 | 30 | Reads from the current version of the atom." 31 | ([cache-atom e] 32 | (force (c/lookup @cache-atom e))) 33 | ([cache-atom e not-found] 34 | (force (c/lookup @cache-atom e not-found)))) 35 | 36 | (def ^{:private true} default-wrapper-fn #(%1 %2)) 37 | 38 | (defn lookup-or-miss 39 | "Retrieve the value associated with `e` if it exists, else compute the 40 | value (using value-fn, and optionally wrap-fn), update the cache for `e` 41 | and then perform the lookup again. 42 | 43 | value-fn (and wrap-fn) will only be called (at most) once even in the 44 | case of retries, so there is no risk of cache stampede. 45 | 46 | Since lookup can cause invalidation in some caches (such as TTL), we 47 | trap that case and retry (a maximum of ten times)." 48 | ([cache-atom e value-fn] 49 | (lookup-or-miss cache-atom e default-wrapper-fn value-fn)) 50 | ([cache-atom e wrap-fn value-fn] 51 | (let [d-new-value (delay (wrap-fn value-fn e))] 52 | (loop [n 0 53 | v (force (c/lookup (swap! cache-atom 54 | c/through-cache 55 | e 56 | default-wrapper-fn 57 | (fn [_] d-new-value)) 58 | e 59 | ::expired))] 60 | (when (< n 10) 61 | (if (= ::expired v) 62 | (recur (inc n) 63 | (force (c/lookup (swap! cache-atom 64 | c/through-cache 65 | e 66 | default-wrapper-fn 67 | (fn [_] d-new-value)) 68 | e 69 | ::expired))) 70 | v)))))) 71 | 72 | (defn has? 73 | "Checks if the cache contains a value associated with `e`. 74 | 75 | Reads from the current version of the atom." 76 | [cache-atom e] 77 | (c/has? @cache-atom e)) 78 | 79 | (defn hit 80 | "Is meant to be called if the cache is determined to contain a value 81 | associated with `e`. 82 | 83 | Returns the updated cache from the atom. Provided for completeness." 84 | [cache-atom e] 85 | (swap! cache-atom c/hit e)) 86 | 87 | (defn miss 88 | "Is meant to be called if the cache is determined to **not** contain a 89 | value associated with `e`. 90 | 91 | Returns the updated cache from the atom. Provided for completeness." 92 | [cache-atom e ret] 93 | (swap! cache-atom c/miss e ret)) 94 | 95 | (defn evict 96 | "Removes an entry from the cache. 97 | 98 | Returns the updated cache from the atom." 99 | [cache-atom e] 100 | (swap! cache-atom c/evict e)) 101 | 102 | (defn seed 103 | "Is used to signal that the cache should be created with a seed. 104 | The contract is that said cache should return an instance of its 105 | own type. 106 | 107 | Returns the updated cache from the atom. Provided for completeness." 108 | [cache-atom base] 109 | (swap! cache-atom c/seed base)) 110 | 111 | (defn through 112 | "The basic hit/miss logic for the cache system. Expects a wrap function and 113 | value function. The wrap function takes the value function and the item in question 114 | and is expected to run the value function with the item whenever a cache 115 | miss occurs. The intent is to hide any cache-specific cells from leaking 116 | into the cache logic itelf." 117 | ([cache-atom item] (through default-wrapper-fn identity cache-atom item)) 118 | ([value-fn cache-atom item] (through default-wrapper-fn value-fn cache-atom item)) 119 | ([wrap-fn value-fn cache-atom item] 120 | (swap! cache-atom c/through-cache item wrap-fn value-fn))) 121 | 122 | (defn through-cache 123 | "The basic hit/miss logic for the cache system. Like through but always has 124 | the cache argument in the first position." 125 | ([cache-atom item] (through-cache cache-atom item default-wrapper-fn identity)) 126 | ([cache-atom item value-fn] (through-cache cache-atom item default-wrapper-fn value-fn)) 127 | ([cache-atom item wrap-fn value-fn] 128 | (swap! cache-atom c/through-cache item wrap-fn value-fn))) 129 | 130 | (defn basic-cache-factory 131 | "Returns a pluggable basic cache initialized to `base`" 132 | [base] 133 | (atom (c/basic-cache-factory base))) 134 | 135 | (defn fifo-cache-factory 136 | "Returns a FIFO cache with the cache and FIFO queue initialized to `base` -- 137 | the queue is filled as the values are pulled out of `base`. If the associative 138 | structure can guarantee ordering, then the said ordering will define the 139 | eventual eviction order. Otherwise, there are no guarantees for the eventual 140 | eviction ordering. 141 | 142 | This function takes an optional `:threshold` argument that defines the maximum number 143 | of elements in the cache before the FIFO semantics apply (default is 32). 144 | 145 | If the number of elements in `base` is greater than the limit then some items 146 | in `base` will be dropped from the resulting cache. If the associative 147 | structure used as `base` can guarantee sorting, then the last `limit` elements 148 | will be used as the cache seed values. Otherwise, there are no guarantees about 149 | the elements in the resulting cache." 150 | [base & {threshold :threshold :or {threshold 32}}] 151 | (atom (c/fifo-cache-factory base :threshold threshold))) 152 | 153 | (defn lru-cache-factory 154 | "Returns an LRU cache with the cache and usage-table initialized to `base` -- 155 | each entry is initialized with the same usage value. 156 | 157 | This function takes an optional `:threshold` argument that defines the maximum number 158 | of elements in the cache before the LRU semantics apply (default is 32)." 159 | [base & {threshold :threshold :or {threshold 32}}] 160 | (atom (c/lru-cache-factory base :threshold threshold))) 161 | 162 | (defn ttl-cache-factory 163 | "Returns a TTL cache with the cache and expiration-table initialized to `base` -- 164 | each with the same time-to-live. 165 | 166 | This function also allows an optional `:ttl` argument that defines the default 167 | time in milliseconds that entries are allowed to reside in the cache." 168 | [base & {ttl :ttl :or {ttl 2000}}] 169 | (atom (c/ttl-cache-factory base :ttl ttl))) 170 | 171 | (defn lu-cache-factory 172 | "Returns an LU cache with the cache and usage-table initialized to `base`. 173 | 174 | This function takes an optional `:threshold` argument that defines the maximum number 175 | of elements in the cache before the LU semantics apply (default is 32)." 176 | [base & {threshold :threshold :or {threshold 32}}] 177 | (atom (c/lu-cache-factory base :threshold threshold))) 178 | 179 | (defn lirs-cache-factory 180 | "Returns an LIRS cache with the S & R LRU lists set to the indicated 181 | limits." 182 | [base & {:keys [s-history-limit q-history-limit] 183 | :or {s-history-limit 32 184 | q-history-limit 32}}] 185 | (atom (c/lirs-cache-factory base 186 | :s-history-limit s-history-limit 187 | :q-history-limit q-history-limit))) 188 | 189 | (defn soft-cache-factory 190 | "Returns a SoftReference cache. Cached values will be referred to with 191 | SoftReferences, allowing the values to be garbage collected when there is 192 | memory pressure on the JVM. 193 | 194 | SoftCache is a mutable cache, since it is always based on a 195 | ConcurrentHashMap." 196 | [base] 197 | (atom (c/soft-cache-factory base))) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Eclipse Public License - v 1.0 2 | 3 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 4 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 5 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 6 | 7 | 1. DEFINITIONS 8 | 9 | "Contribution" means: 10 | 11 | a) in the case of the initial Contributor, the initial code and documentation 12 | distributed under this Agreement, and 13 | b) in the case of each subsequent Contributor: 14 | i) changes to the Program, and 15 | ii) additions to the Program; 16 | 17 | where such changes and/or additions to the Program originate from and are 18 | distributed by that particular Contributor. A Contribution 'originates' 19 | from a Contributor if it was added to the Program by such Contributor 20 | itself or anyone acting on such Contributor's behalf. Contributions do not 21 | include additions to the Program which: (i) are separate modules of 22 | software distributed in conjunction with the Program under their own 23 | license agreement, and (ii) are not derivative works of the Program. 24 | 25 | "Contributor" means any person or entity that distributes the Program. 26 | 27 | "Licensed Patents" mean patent claims licensable by a Contributor which are 28 | necessarily infringed by the use or sale of its Contribution alone or when 29 | combined with the Program. 30 | 31 | "Program" means the Contributions distributed in accordance with this 32 | Agreement. 33 | 34 | "Recipient" means anyone who receives the Program under this Agreement, 35 | including all Contributors. 36 | 37 | 2. GRANT OF RIGHTS 38 | a) Subject to the terms of this Agreement, each Contributor hereby grants 39 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 40 | reproduce, prepare derivative works of, publicly display, publicly 41 | perform, distribute and sublicense the Contribution of such Contributor, 42 | if any, and such derivative works, in source code and object code form. 43 | b) Subject to the terms of this Agreement, each Contributor hereby grants 44 | Recipient a non-exclusive, worldwide, royalty-free patent license under 45 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 46 | transfer the Contribution of such Contributor, if any, in source code and 47 | object code form. This patent license shall apply to the combination of 48 | the Contribution and the Program if, at the time the Contribution is 49 | added by the Contributor, such addition of the Contribution causes such 50 | combination to be covered by the Licensed Patents. The patent license 51 | shall not apply to any other combinations which include the Contribution. 52 | No hardware per se is licensed hereunder. 53 | c) Recipient understands that although each Contributor grants the licenses 54 | to its Contributions set forth herein, no assurances are provided by any 55 | Contributor that the Program does not infringe the patent or other 56 | intellectual property rights of any other entity. Each Contributor 57 | disclaims any liability to Recipient for claims brought by any other 58 | entity based on infringement of intellectual property rights or 59 | otherwise. As a condition to exercising the rights and licenses granted 60 | hereunder, each Recipient hereby assumes sole responsibility to secure 61 | any other intellectual property rights needed, if any. For example, if a 62 | third party patent license is required to allow Recipient to distribute 63 | the Program, it is Recipient's responsibility to acquire that license 64 | before distributing the Program. 65 | d) Each Contributor represents that to its knowledge it has sufficient 66 | copyright rights in its Contribution, if any, to grant the copyright 67 | license set forth in this Agreement. 68 | 69 | 3. REQUIREMENTS 70 | 71 | A Contributor may choose to distribute the Program in object code form under 72 | its own license agreement, provided that: 73 | 74 | a) it complies with the terms and conditions of this Agreement; and 75 | b) its license agreement: 76 | i) effectively disclaims on behalf of all Contributors all warranties 77 | and conditions, express and implied, including warranties or 78 | conditions of title and non-infringement, and implied warranties or 79 | conditions of merchantability and fitness for a particular purpose; 80 | ii) effectively excludes on behalf of all Contributors all liability for 81 | damages, including direct, indirect, special, incidental and 82 | consequential damages, such as lost profits; 83 | iii) states that any provisions which differ from this Agreement are 84 | offered by that Contributor alone and not by any other party; and 85 | iv) states that source code for the Program is available from such 86 | Contributor, and informs licensees how to obtain it in a reasonable 87 | manner on or through a medium customarily used for software exchange. 88 | 89 | When the Program is made available in source code form: 90 | 91 | a) it must be made available under this Agreement; and 92 | b) a copy of this Agreement must be included with each copy of the Program. 93 | Contributors may not remove or alter any copyright notices contained 94 | within the Program. 95 | 96 | Each Contributor must identify itself as the originator of its Contribution, 97 | if 98 | any, in a manner that reasonably allows subsequent Recipients to identify the 99 | originator of the Contribution. 100 | 101 | 4. COMMERCIAL DISTRIBUTION 102 | 103 | Commercial distributors of software may accept certain responsibilities with 104 | respect to end users, business partners and the like. While this license is 105 | intended to facilitate the commercial use of the Program, the Contributor who 106 | includes the Program in a commercial product offering should do so in a manner 107 | which does not create potential liability for other Contributors. Therefore, 108 | if a Contributor includes the Program in a commercial product offering, such 109 | Contributor ("Commercial Contributor") hereby agrees to defend and indemnify 110 | every other Contributor ("Indemnified Contributor") against any losses, 111 | damages and costs (collectively "Losses") arising from claims, lawsuits and 112 | other legal actions brought by a third party against the Indemnified 113 | Contributor to the extent caused by the acts or omissions of such Commercial 114 | Contributor in connection with its distribution of the Program in a commercial 115 | product offering. The obligations in this section do not apply to any claims 116 | or Losses relating to any actual or alleged intellectual property 117 | infringement. In order to qualify, an Indemnified Contributor must: 118 | a) promptly notify the Commercial Contributor in writing of such claim, and 119 | b) allow the Commercial Contributor to control, and cooperate with the 120 | Commercial Contributor in, the defense and any related settlement 121 | negotiations. The Indemnified Contributor may participate in any such claim at 122 | its own expense. 123 | 124 | For example, a Contributor might include the Program in a commercial product 125 | offering, Product X. That Contributor is then a Commercial Contributor. If 126 | that Commercial Contributor then makes performance claims, or offers 127 | warranties related to Product X, those performance claims and warranties are 128 | such Commercial Contributor's responsibility alone. Under this section, the 129 | Commercial Contributor would have to defend claims against the other 130 | Contributors related to those performance claims and warranties, and if a 131 | court requires any other Contributor to pay any damages as a result, the 132 | Commercial Contributor must pay those damages. 133 | 134 | 5. NO WARRANTY 135 | 136 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN 137 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR 138 | IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each 140 | Recipient is solely responsible for determining the appropriateness of using 141 | and distributing the Program and assumes all risks associated with its 142 | exercise of rights under this Agreement , including but not limited to the 143 | risks and costs of program errors, compliance with applicable laws, damage to 144 | or loss of data, programs or equipment, and unavailability or interruption of 145 | operations. 146 | 147 | 6. DISCLAIMER OF LIABILITY 148 | 149 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 150 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 151 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 152 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 153 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 154 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 155 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 156 | OF SUCH DAMAGES. 157 | 158 | 7. GENERAL 159 | 160 | If any provision of this Agreement is invalid or unenforceable under 161 | applicable law, it shall not affect the validity or enforceability of the 162 | remainder of the terms of this Agreement, and without further action by the 163 | parties hereto, such provision shall be reformed to the minimum extent 164 | necessary to make such provision valid and enforceable. 165 | 166 | If Recipient institutes patent litigation against any entity (including a 167 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 168 | (excluding combinations of the Program with other software or hardware) 169 | infringes such Recipient's patent(s), then such Recipient's rights granted 170 | under Section 2(b) shall terminate as of the date such litigation is filed. 171 | 172 | All Recipient's rights under this Agreement shall terminate if it fails to 173 | comply with any of the material terms or conditions of this Agreement and does 174 | not cure such failure in a reasonable period of time after becoming aware of 175 | such noncompliance. If all Recipient's rights under this Agreement terminate, 176 | Recipient agrees to cease use and distribution of the Program as soon as 177 | reasonably practicable. However, Recipient's obligations under this Agreement 178 | and any licenses granted by Recipient relating to the Program shall continue 179 | and survive. 180 | 181 | Everyone is permitted to copy and distribute copies of this Agreement, but in 182 | order to avoid inconsistency the Agreement is copyrighted and may only be 183 | modified in the following manner. The Agreement Steward reserves the right to 184 | publish new versions (including revisions) of this Agreement from time to 185 | time. No one other than the Agreement Steward has the right to modify this 186 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 187 | Eclipse Foundation may assign the responsibility to serve as the Agreement 188 | Steward to a suitable separate entity. Each new version of the Agreement will 189 | be given a distinguishing version number. The Program (including 190 | Contributions) may always be distributed subject to the version of the 191 | Agreement under which it was received. In addition, after a new version of the 192 | Agreement is published, Contributor may elect to distribute the Program 193 | (including its Contributions) under the new version. Except as expressly 194 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 195 | licenses to the intellectual property of any Contributor under this Agreement, 196 | whether expressly, by implication, estoppel or otherwise. All rights in the 197 | Program not expressly granted under this Agreement are reserved. 198 | 199 | This Agreement is governed by the laws of the State of New York and the 200 | intellectual property laws of the United States of America. No party to this 201 | Agreement will bring a legal action under this Agreement more than one year 202 | after the cause of action arose. Each party waives its rights to a jury trial in 203 | any resulting litigation. 204 | 205 | -------------------------------------------------------------------------------- /epl.html: -------------------------------------------------------------------------------- 1 | Eclipse Public License - v 1.0 2 | 3 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 4 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 5 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 6 | 7 | 1. DEFINITIONS 8 | 9 | "Contribution" means: 10 | 11 | a) in the case of the initial Contributor, the initial code and documentation 12 | distributed under this Agreement, and 13 | b) in the case of each subsequent Contributor: 14 | i) changes to the Program, and 15 | ii) additions to the Program; 16 | 17 | where such changes and/or additions to the Program originate from and are 18 | distributed by that particular Contributor. A Contribution 'originates' 19 | from a Contributor if it was added to the Program by such Contributor 20 | itself or anyone acting on such Contributor's behalf. Contributions do not 21 | include additions to the Program which: (i) are separate modules of 22 | software distributed in conjunction with the Program under their own 23 | license agreement, and (ii) are not derivative works of the Program. 24 | 25 | "Contributor" means any person or entity that distributes the Program. 26 | 27 | "Licensed Patents" mean patent claims licensable by a Contributor which are 28 | necessarily infringed by the use or sale of its Contribution alone or when 29 | combined with the Program. 30 | 31 | "Program" means the Contributions distributed in accordance with this 32 | Agreement. 33 | 34 | "Recipient" means anyone who receives the Program under this Agreement, 35 | including all Contributors. 36 | 37 | 2. GRANT OF RIGHTS 38 | a) Subject to the terms of this Agreement, each Contributor hereby grants 39 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 40 | reproduce, prepare derivative works of, publicly display, publicly 41 | perform, distribute and sublicense the Contribution of such Contributor, 42 | if any, and such derivative works, in source code and object code form. 43 | b) Subject to the terms of this Agreement, each Contributor hereby grants 44 | Recipient a non-exclusive, worldwide, royalty-free patent license under 45 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 46 | transfer the Contribution of such Contributor, if any, in source code and 47 | object code form. This patent license shall apply to the combination of 48 | the Contribution and the Program if, at the time the Contribution is 49 | added by the Contributor, such addition of the Contribution causes such 50 | combination to be covered by the Licensed Patents. The patent license 51 | shall not apply to any other combinations which include the Contribution. 52 | No hardware per se is licensed hereunder. 53 | c) Recipient understands that although each Contributor grants the licenses 54 | to its Contributions set forth herein, no assurances are provided by any 55 | Contributor that the Program does not infringe the patent or other 56 | intellectual property rights of any other entity. Each Contributor 57 | disclaims any liability to Recipient for claims brought by any other 58 | entity based on infringement of intellectual property rights or 59 | otherwise. As a condition to exercising the rights and licenses granted 60 | hereunder, each Recipient hereby assumes sole responsibility to secure 61 | any other intellectual property rights needed, if any. For example, if a 62 | third party patent license is required to allow Recipient to distribute 63 | the Program, it is Recipient's responsibility to acquire that license 64 | before distributing the Program. 65 | d) Each Contributor represents that to its knowledge it has sufficient 66 | copyright rights in its Contribution, if any, to grant the copyright 67 | license set forth in this Agreement. 68 | 69 | 3. REQUIREMENTS 70 | 71 | A Contributor may choose to distribute the Program in object code form under 72 | its own license agreement, provided that: 73 | 74 | a) it complies with the terms and conditions of this Agreement; and 75 | b) its license agreement: 76 | i) effectively disclaims on behalf of all Contributors all warranties 77 | and conditions, express and implied, including warranties or 78 | conditions of title and non-infringement, and implied warranties or 79 | conditions of merchantability and fitness for a particular purpose; 80 | ii) effectively excludes on behalf of all Contributors all liability for 81 | damages, including direct, indirect, special, incidental and 82 | consequential damages, such as lost profits; 83 | iii) states that any provisions which differ from this Agreement are 84 | offered by that Contributor alone and not by any other party; and 85 | iv) states that source code for the Program is available from such 86 | Contributor, and informs licensees how to obtain it in a reasonable 87 | manner on or through a medium customarily used for software exchange. 88 | 89 | When the Program is made available in source code form: 90 | 91 | a) it must be made available under this Agreement; and 92 | b) a copy of this Agreement must be included with each copy of the Program. 93 | Contributors may not remove or alter any copyright notices contained 94 | within the Program. 95 | 96 | Each Contributor must identify itself as the originator of its Contribution, 97 | if 98 | any, in a manner that reasonably allows subsequent Recipients to identify the 99 | originator of the Contribution. 100 | 101 | 4. COMMERCIAL DISTRIBUTION 102 | 103 | Commercial distributors of software may accept certain responsibilities with 104 | respect to end users, business partners and the like. While this license is 105 | intended to facilitate the commercial use of the Program, the Contributor who 106 | includes the Program in a commercial product offering should do so in a manner 107 | which does not create potential liability for other Contributors. Therefore, 108 | if a Contributor includes the Program in a commercial product offering, such 109 | Contributor ("Commercial Contributor") hereby agrees to defend and indemnify 110 | every other Contributor ("Indemnified Contributor") against any losses, 111 | damages and costs (collectively "Losses") arising from claims, lawsuits and 112 | other legal actions brought by a third party against the Indemnified 113 | Contributor to the extent caused by the acts or omissions of such Commercial 114 | Contributor in connection with its distribution of the Program in a commercial 115 | product offering. The obligations in this section do not apply to any claims 116 | or Losses relating to any actual or alleged intellectual property 117 | infringement. In order to qualify, an Indemnified Contributor must: 118 | a) promptly notify the Commercial Contributor in writing of such claim, and 119 | b) allow the Commercial Contributor to control, and cooperate with the 120 | Commercial Contributor in, the defense and any related settlement 121 | negotiations. The Indemnified Contributor may participate in any such claim at 122 | its own expense. 123 | 124 | For example, a Contributor might include the Program in a commercial product 125 | offering, Product X. That Contributor is then a Commercial Contributor. If 126 | that Commercial Contributor then makes performance claims, or offers 127 | warranties related to Product X, those performance claims and warranties are 128 | such Commercial Contributor's responsibility alone. Under this section, the 129 | Commercial Contributor would have to defend claims against the other 130 | Contributors related to those performance claims and warranties, and if a 131 | court requires any other Contributor to pay any damages as a result, the 132 | Commercial Contributor must pay those damages. 133 | 134 | 5. NO WARRANTY 135 | 136 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN 137 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR 138 | IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each 140 | Recipient is solely responsible for determining the appropriateness of using 141 | and distributing the Program and assumes all risks associated with its 142 | exercise of rights under this Agreement , including but not limited to the 143 | risks and costs of program errors, compliance with applicable laws, damage to 144 | or loss of data, programs or equipment, and unavailability or interruption of 145 | operations. 146 | 147 | 6. DISCLAIMER OF LIABILITY 148 | 149 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 150 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 151 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 152 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 153 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 154 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 155 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 156 | OF SUCH DAMAGES. 157 | 158 | 7. GENERAL 159 | 160 | If any provision of this Agreement is invalid or unenforceable under 161 | applicable law, it shall not affect the validity or enforceability of the 162 | remainder of the terms of this Agreement, and without further action by the 163 | parties hereto, such provision shall be reformed to the minimum extent 164 | necessary to make such provision valid and enforceable. 165 | 166 | If Recipient institutes patent litigation against any entity (including a 167 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 168 | (excluding combinations of the Program with other software or hardware) 169 | infringes such Recipient's patent(s), then such Recipient's rights granted 170 | under Section 2(b) shall terminate as of the date such litigation is filed. 171 | 172 | All Recipient's rights under this Agreement shall terminate if it fails to 173 | comply with any of the material terms or conditions of this Agreement and does 174 | not cure such failure in a reasonable period of time after becoming aware of 175 | such noncompliance. If all Recipient's rights under this Agreement terminate, 176 | Recipient agrees to cease use and distribution of the Program as soon as 177 | reasonably practicable. However, Recipient's obligations under this Agreement 178 | and any licenses granted by Recipient relating to the Program shall continue 179 | and survive. 180 | 181 | Everyone is permitted to copy and distribute copies of this Agreement, but in 182 | order to avoid inconsistency the Agreement is copyrighted and may only be 183 | modified in the following manner. The Agreement Steward reserves the right to 184 | publish new versions (including revisions) of this Agreement from time to 185 | time. No one other than the Agreement Steward has the right to modify this 186 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 187 | Eclipse Foundation may assign the responsibility to serve as the Agreement 188 | Steward to a suitable separate entity. Each new version of the Agreement will 189 | be given a distinguishing version number. The Program (including 190 | Contributions) may always be distributed subject to the version of the 191 | Agreement under which it was received. In addition, after a new version of the 192 | Agreement is published, Contributor may elect to distribute the Program 193 | (including its Contributions) under the new version. Except as expressly 194 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 195 | licenses to the intellectual property of any Contributor under this Agreement, 196 | whether expressly, by implication, estoppel or otherwise. All rights in the 197 | Program not expressly granted under this Agreement are reserved. 198 | 199 | This Agreement is governed by the laws of the State of New York and the 200 | intellectual property laws of the United States of America. No party to this 201 | Agreement will bring a legal action under this Agreement more than one year 202 | after the cause of action arose. Each party waives its rights to a jury trial in 203 | any resulting litigation. 204 | 205 | -------------------------------------------------------------------------------- /src/test/clojure/clojure/core/cache_test.clj: -------------------------------------------------------------------------------- 1 | ; Copyright (c) Rich Hickey. All rights reserved. 2 | ; The use and distribution terms for this software are covered by the 3 | ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) 4 | ; which can be found in the file epl-v10.html at the root of this distribution. 5 | ; By using this software in any fashion, you are agreeing to be bound by 6 | ; the terms of this license. 7 | ; You must not remove this notice, or any other, from this software. 8 | 9 | (ns ^{:doc "A caching library for Clojure." 10 | :author "Fogus"} 11 | clojure.core.cache-test 12 | (:use [clojure.core.cache] :reload-all) 13 | (:use [clojure.test]) 14 | (:import (clojure.core.cache BasicCache FIFOCache LRUCache TTLCacheQ LUCache 15 | LIRSCache) 16 | ;;; (java.lang.ref ReferenceQueue SoftReference) 17 | )) ;;; (java.util.concurrent ConcurrentHashMap) 18 | 19 | (println "\nTesting with Clojure" (clojure-version)) 20 | 21 | (deftest test-basic-cache-lookup 22 | (testing "that the BasicCache can lookup as expected" 23 | (is (= :robot (lookup (miss (BasicCache. {}) '(servo) :robot) '(servo)))))) 24 | 25 | (defn do-dot-lookup-tests [c] 26 | (are [expect actual] (= expect actual) 27 | 1 (.lookup c :a) 28 | 2 (.lookup c :b) 29 | 42 (.lookup c :c 42) 30 | nil (.lookup c :c))) 31 | 32 | (defn do-ilookup-tests [c] 33 | (are [expect actual] (= expect actual) 34 | 1 (:a c) 35 | 2 (:b c) 36 | 42 (:X c 42) 37 | nil (:X c))) 38 | 39 | (defn do-assoc [c] 40 | (are [expect actual] (= expect actual) 41 | 1 (:a (assoc c :a 1)) 42 | nil (:a (assoc c :b 1)))) 43 | 44 | (defn do-dissoc [c] 45 | (are [expect actual] (= expect actual) 46 | 2 (:b (dissoc c :a)) 47 | nil (:a (dissoc c :a)) 48 | nil (:b (-> c (dissoc :a) (dissoc :b))) 49 | 0 (count (-> c (dissoc :a) (dissoc :b))))) 50 | 51 | (defn do-getting [c] 52 | (are [actual expect] (= expect actual) 53 | (get c :a) 1 54 | (get c :e) nil 55 | (get c :e 0) 0 56 | (get c :b 0) 2 57 | (get c :f 0) nil 58 | 59 | (get-in c [:c :e]) 4 60 | (get-in c '(:c :e)) 4 61 | (get-in c [:c :x]) nil 62 | (get-in c [:f]) nil 63 | (get-in c [:g]) false 64 | (get-in c [:h]) nil 65 | (get-in c []) c 66 | (get-in c nil) c 67 | 68 | (get-in c [:c :e] 0) 4 69 | (get-in c '(:c :e) 0) 4 70 | (get-in c [:c :x] 0) 0 71 | (get-in c [:b] 0) 2 72 | (get-in c [:f] 0) nil 73 | (get-in c [:g] 0) false 74 | (get-in c [:h] 0) 0 75 | (get-in c [:x :y] {:y 1}) {:y 1} 76 | (get-in c [] 0) c 77 | (get-in c nil 0) c)) 78 | 79 | (defn do-finding [c] 80 | (are [expect actual] (= expect actual) 81 | (find c :a) [:a 1] 82 | (find c :b) [:b 2] 83 | (find c :c) nil 84 | (find c nil) nil)) 85 | 86 | (defn do-contains [c] 87 | (are [expect actual] (= expect actual) 88 | (contains? c :a) true 89 | (contains? c :b) true 90 | (contains? c :c) false 91 | (contains? c nil) false)) 92 | 93 | 94 | (def big-map {:a 1, :b 2, :c {:d 3, :e 4}, :f nil, :g false, nil {:h 5}}) 95 | (def small-map {:a 1 :b 2}) 96 | 97 | (deftest test-basic-cache-ilookup 98 | (testing "counts" 99 | (is (= 0 (count (BasicCache. {})))) 100 | (is (= 1 (count (BasicCache. {:a 1}))))) 101 | (testing "that the BasicCache can lookup via keywords" 102 | (do-ilookup-tests (BasicCache. small-map))) 103 | (testing "that the BasicCache can .lookup" 104 | (do-dot-lookup-tests (BasicCache. small-map))) 105 | (testing "assoc and dissoc for BasicCache" 106 | (do-assoc (BasicCache. {})) 107 | (do-dissoc (BasicCache. {:a 1 :b 2}))) 108 | (testing "that get and cascading gets work for BasicCache" 109 | (do-getting (BasicCache. big-map))) 110 | (testing "that finding works for BasicCache" 111 | (do-finding (BasicCache. small-map))) 112 | (testing "that contains? works for BasicCache" 113 | (do-contains (BasicCache. small-map)))) 114 | 115 | (deftest test-fifo-cache-ilookup 116 | (testing "that the FifoCache can lookup via keywords" 117 | (do-ilookup-tests (FIFOCache. small-map clojure.lang.PersistentQueue/EMPTY 2))) 118 | (testing "that the FifoCache can lookup via keywords" 119 | (do-dot-lookup-tests (FIFOCache. small-map clojure.lang.PersistentQueue/EMPTY 2))) 120 | (testing "assoc and dissoc for FifoCache" 121 | (do-assoc (FIFOCache. {} clojure.lang.PersistentQueue/EMPTY 2)) 122 | (do-dissoc (FIFOCache. {:a 1 :b 2} clojure.lang.PersistentQueue/EMPTY 2))) 123 | (testing "that get and cascading gets work for FifoCache" 124 | (do-getting (FIFOCache. big-map clojure.lang.PersistentQueue/EMPTY 2))) 125 | (testing "that finding works for FifoCache" 126 | (do-finding (FIFOCache. small-map clojure.lang.PersistentQueue/EMPTY 2))) 127 | (testing "that contains? works for FifoCache" 128 | (do-contains (FIFOCache. small-map clojure.lang.PersistentQueue/EMPTY 2))) 129 | (testing "that FIFO caches starting with less elements than the threshold work" 130 | (let [C (fifo-cache-factory (sorted-map :a 1, :b 2) :threshold 3)] 131 | (are [x y] (= x y) 132 | {:a 1, :b 2, :c 3} (.cache (assoc C :c 3)) 133 | {:d 4, :b 2, :c 3} (.cache (assoc C :c 3 :d 4)))))) 134 | 135 | (deftest test-lru-cache-ilookup 136 | (testing "that the LRUCache can lookup via keywords" 137 | (do-ilookup-tests (LRUCache. small-map {} 0 2))) 138 | (testing "that the LRUCache can lookup via keywords" 139 | (do-dot-lookup-tests (LRUCache. small-map {} 0 2))) 140 | (testing "assoc and dissoc for LRUCache" 141 | (do-assoc (LRUCache. {} {} 0 2)) 142 | (do-dissoc (LRUCache. {:a 1 :b 2} {} 0 2))) 143 | (testing "that get and cascading gets work for LRUCache" 144 | (do-getting (LRUCache. big-map {} 0 2))) 145 | (testing "that finding works for LRUCache" 146 | (do-finding (LRUCache. small-map {} 0 2))) 147 | (testing "that contains? works for LRUCache" 148 | (do-contains (LRUCache. small-map {} 0 2)))) 149 | 150 | (deftest test-lru-cache 151 | (testing "LRU-ness with empty cache and threshold 2" 152 | (let [C (lru-cache-factory {} :threshold 2)] 153 | (are [x y] (= x y) 154 | {:a 1, :b 2} (-> C (assoc :a 1) (assoc :b 2) .cache) 155 | {:b 2, :c 3} (-> C (assoc :a 1) (assoc :b 2) (assoc :c 3) .cache) 156 | {:a 1, :c 3} (-> C (assoc :a 1) (assoc :b 2) (.hit :a) (assoc :c 3) .cache)))) 157 | (testing "LRU-ness with seeded cache and threshold 4" 158 | (let [C (lru-cache-factory {:a 1, :b 2} :threshold 4)] 159 | (are [x y] (= x y) 160 | {:a 1, :b 2, :c 3, :d 4} (-> C (assoc :c 3) (assoc :d 4) .cache) 161 | {:a 1, :c 3, :d 4, :e 5} (-> C (assoc :c 3) (assoc :d 4) (.hit :c) (.hit :a) (assoc :e 5) .cache)))) 162 | (testing "regressions against LRU eviction before threshold met" 163 | (is (= {:b 3 :a 4} 164 | (-> (clojure.core.cache/lru-cache-factory {} :threshold 2) 165 | (assoc :a 1) 166 | (assoc :b 2) 167 | (assoc :b 3) 168 | (assoc :a 4) 169 | .cache))) 170 | 171 | (is (= {:e 6, :d 5, :c 4} 172 | (-> (clojure.core.cache/lru-cache-factory {} :threshold 3) 173 | (assoc :a 1) 174 | (assoc :b 2) 175 | (assoc :b 3) 176 | (assoc :c 4) 177 | (assoc :d 5) 178 | (assoc :e 6) 179 | .cache))) 180 | 181 | (is (= {:a 1 :b 3} 182 | (-> (clojure.core.cache/lru-cache-factory {} :threshold 2) 183 | (assoc :a 1) 184 | (assoc :b 2) 185 | (assoc :b 3) 186 | .cache)))) 187 | 188 | (is (= {:d 4 :e 5} 189 | (-> (lru-cache-factory {} :threshold 2) 190 | (hit :x) 191 | (hit :y) 192 | (hit :z) 193 | (assoc :a 1) 194 | (assoc :b 2) 195 | (assoc :c 3) 196 | (assoc :d 4) 197 | (assoc :e 5) 198 | .cache)))) 199 | 200 | (defn sleepy [e t] (System.Threading.Thread/Sleep t) e) ;;; sleep 201 | 202 | (deftest test-ttl-cache-ilookup 203 | (let [five-secs (+ 5000 (Environment/TickCount)) ;;; System/currentTimeMillis 204 | big-time (into {} (for [[k _] big-map] [k [0 five-secs]])) 205 | big-q (into clojure.lang.PersistentQueue/EMPTY 206 | (for [[k _] big-map] [k 0 five-secs])) 207 | small-time (into {} (for [[k _] small-map] [k [0 five-secs]])) 208 | small-q (into clojure.lang.PersistentQueue/EMPTY 209 | (for [[k _] small-map] [k 0 five-secs]))] 210 | (testing "that the TTLCacheQ can lookup via keywords" 211 | (do-ilookup-tests (TTLCacheQ. small-map small-time small-q 1 2000))) 212 | (testing "that the TTLCacheQ can lookup via keywords" 213 | (do-dot-lookup-tests (TTLCacheQ. small-map small-time small-q 1 2000))) 214 | (testing "assoc and dissocQ for TTLCacheQ" 215 | (do-assoc (TTLCacheQ. {} {} clojure.lang.PersistentQueue/EMPTY 1 2000)) 216 | (do-dissoc (TTLCacheQ. {:a 1 :b 2} 217 | {:a [0 five-secs] :b [0 five-secs]} 218 | (into clojure.lang.PersistentQueue/EMPTY 219 | [[:a 0 five-secs] [:b 0 five-secs]]) 220 | 1 221 | 2000))) 222 | (testing "that get and cascading gets work for TTLCacheQ" 223 | (do-getting (TTLCacheQ. big-map big-time big-q 1 2000))) 224 | (testing "that finding works for TTLCacheQ" 225 | (do-finding (TTLCacheQ. small-map small-time small-q 1 2000))) 226 | (testing "that contains? works for TTLCacheQ" 227 | (do-contains (TTLCacheQ. small-map small-time small-q 1 2000))))) 228 | 229 | (defn- ttl-q-check 230 | [start nap [k g t]] 231 | [k g (<= start (+ start nap) t (+ start nap 100))]) 232 | 233 | (deftest test-ttl-cache 234 | (testing "TTL-ness with empty cache" 235 | (let [start (Environment/TickCount) ;;; System/currentTimeMillis 236 | C (ttl-cache-factory {} :ttl 500) 237 | C' (-> C (assoc :a 1) (assoc :b 2))] 238 | (are [x y] (= x y) 239 | [[:a 1 true], [:b 2 true]] (map (partial ttl-q-check start 0) (.q C')) 240 | {:a 1, :b 2} (.cache C') 241 | 3 (.gen C'))) 242 | (let [start (Environment/TickCount) ;;; System/currentTimeMillis 243 | C (ttl-cache-factory {} :ttl 500) 244 | C' (-> C (assoc :a 1) (assoc :b 2) (sleepy 700) (assoc :c 3))] 245 | (are [x y] (= x y) 246 | [[:c 3 true]] (map (partial ttl-q-check start 700) (.q C')) 247 | {:c 3} (.cache C') 248 | 4 (.gen C')))) 249 | (testing "TTL cache does not return a value that has expired." 250 | (let [C (ttl-cache-factory {} :ttl 500)] 251 | (is (nil? (-> C (assoc :a 1) (sleepy 700) (lookup :a)))))) 252 | (testing "TTL cache does not contain a value that was removed from underlying cache." 253 | (let [underlying-cache (lru-cache-factory {} :threshold 1) 254 | C (ttl-cache-factory underlying-cache :ttl 360000)] 255 | (is (not (-> C (assoc :a 1) (assoc :b 2) (has? :a))))))) 256 | 257 | (deftest test-lu-cache-ilookup 258 | (testing "that the LUCache can lookup via keywords" 259 | (do-ilookup-tests (LUCache. small-map {} 2))) 260 | (testing "that the LUCache can lookup via keywords" 261 | (do-dot-lookup-tests (LUCache. small-map {} 2))) 262 | (testing "assoc and dissoc for LUCache" 263 | (do-assoc (LUCache. {} {} 2)) 264 | (do-dissoc (LUCache. {:a 1 :b 2} {} 2)))) 265 | 266 | (deftest test-lu-cache 267 | (testing "LU-ness with empty cache" 268 | (let [C (lu-cache-factory {} :threshold 2)] 269 | (are [x y] (= x y) 270 | {:a 1, :b 2} (-> C (assoc :a 1) (assoc :b 2) .cache) 271 | {:b 2, :c 3} (-> C (assoc :a 1) (assoc :b 2) (.hit :b) (assoc :c 3) .cache) 272 | {:b 2, :c 3} (-> C (assoc :a 1) (assoc :b 2) (.hit :b) (.hit :b) (.hit :a) (assoc :c 3) .cache)))) 273 | (testing "LU-ness with seeded cache" 274 | (let [C (lu-cache-factory {:a 1, :b 2} :threshold 4)] 275 | (are [x y] (= x y) 276 | {:a 1, :b 2, :c 3, :d 4} (-> C (assoc :c 3) (assoc :d 4) .cache) 277 | {:a 1, :c 3, :d 4, :e 5} (-> C (assoc :c 3) (assoc :d 4) (.hit :a) (assoc :e 5) .cache) 278 | {: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)))) 279 | (testing "regressions against LU eviction before threshold met" 280 | (is (= (-> (clojure.core.cache/lu-cache-factory {} :threshold 2) 281 | (assoc :a 1) 282 | (assoc :b 2) 283 | (assoc :b 3) 284 | (assoc :a 4)) 285 | {:b 3 :a 4})) 286 | 287 | (is (= (-> (clojure.core.cache/lu-cache-factory {} :threshold 3) 288 | (assoc :a 1) 289 | (assoc :b 2) 290 | (assoc :b 3) 291 | (assoc :c 4) 292 | (assoc :d -5) 293 | ;; ensure that the test result does not rely on 294 | ;; arbitrary tie-breakers in number of hits 295 | (assoc :d 5) 296 | (assoc :e 6)) 297 | {:e 6, :d 5, :b 3})) 298 | 299 | (is (= {:a 1 :b 3} 300 | (-> (clojure.core.cache/lu-cache-factory {} :threshold 2) 301 | (assoc :a 1) 302 | (assoc :b 2) 303 | (assoc :b 3) 304 | .cache))) 305 | 306 | (is (= {:c 3 :d 4} 307 | (-> (clojure.core.cache/lu-cache-factory {:a 1 :b 2} :threshold 2) 308 | (dissoc :a) 309 | (assoc :c 3) 310 | (assoc :d 4) 311 | .cache))))) 312 | 313 | ;; # LIRS 314 | 315 | (defn- lirs-map [lirs] 316 | {:cache (.cache lirs) 317 | :lruS (.lruS lirs) 318 | :lruQ (.lruQ lirs) 319 | :tick (.tick lirs) 320 | :limitS (.limitS lirs) 321 | :limitQ (.limitQ lirs)}) 322 | 323 | (deftest test-LIRSCache 324 | (testing "that the LIRSCache can lookup as expected" 325 | (is (= :robot (lookup (miss (seed (LIRSCache. {} {} {} 0 1 1) {}) '(servo) :robot) '(servo))))) 326 | 327 | (testing "a hit of a LIR block: 328 | 329 | L LIR block 330 | H HIR block 331 | N non-resident HIR block 332 | 333 | 334 | +-----------------------------+ +----------------+ 335 | | HIT 4 | | HIT 8 | 336 | | v | | 337 | | | | 338 | H 5 | L 4 | v 339 | H 3 | H 5 | 340 | N 2 | H 3 | L 8 341 | L 1 | N 2 | L 4 342 | N 6 | L 1 | H 5 343 | N 9 | N 6 | H 3 344 | L 4---+ 5 N 9 | 5 N 2 5 345 | L 8 3 L 8---+ 3 L 1 3 346 | 347 | S Q S Q S Q 348 | 349 | " 350 | (let [lirs (LIRSCache. {:1 1 :3 3 :4 4 :5 5 :8 8} 351 | {:5 7 :3 6 :2 5 :1 4 :6 3 :9 2 :4 1 :8 0} 352 | {:5 1 :3 0} 7 3 2)] 353 | (testing "hit 4" 354 | (is (= (lirs-map (hit lirs :4)) 355 | (lirs-map (LIRSCache. {:1 1 :3 3 :4 4 :5 5 :8 8} 356 | {:5 7 :3 6 :2 5 :1 4 :6 3 :9 2 :4 8 :8 0} 357 | {:5 1 :3 0} 8 3 2))))) 358 | (testing "hit 8 prunes the stack" 359 | (is (= (lirs-map (-> lirs (hit :4) (hit :8))) 360 | (lirs-map (LIRSCache. {:1 1 :3 3 :4 4 :5 5 :8 8} 361 | {:5 7 :3 6 :2 5 :1 4 :4 8 :8 9} 362 | {:5 1 :3 0} 9 3 2))))))) 363 | (testing "a hit of a HIR block: 364 | 365 | L LIR block 366 | H HIR block 367 | N non-resident HIR block 368 | 369 | 370 | HIT 3 HIT 5 371 | +-----------------------------+ +------------------+-----+ 372 | | | | | | 373 | L 4 |+----------------------------+-----+ | v | 374 | L 8 || v | | | 375 | H 5 || v | H 5 v 376 | H 3-- | L 3 | L 3 377 | N 2 | 5 L 4 1 | L 4 5 378 | L 1---+ 3 L 8 5---+ L 8 1 379 | 380 | S Q S Q S Q 381 | 382 | " 383 | (let [lirs (LIRSCache. {:1 1 :3 3 :4 4 :5 5 :8 8} 384 | {:4 9 :8 8 :5 7 :3 6 :2 5 :1 4} 385 | {:5 1 :3 0} 9 3 2)] 386 | (testing "hit 3 prunes the stack and moves oldest block of lruS to lruQ" 387 | (is (= (lirs-map (hit lirs :3)) 388 | {:cache {:1 1 :3 3 :4 4 :5 5 :8 8} 389 | :lruS {:3 10 :4 9 :8 8} 390 | :lruQ {:1 10 :5 1} 391 | :tick 10 :limitS 3 :limitQ 2}))) 392 | (testing "hit 5 adds the block to lruS" 393 | (is (= (lirs-map (-> lirs (hit :3) (hit :5))) 394 | {:cache {:1 1 :3 3 :4 4 :5 5 :8 8} 395 | :lruS {:5 11 :3 10 :4 9 :8 8} 396 | :lruQ {:5 11 :1 10} 397 | :tick 11 :limitS 3 :limitQ 2}))))) 398 | (testing "a miss: 399 | 400 | L LIR block 401 | H HIR block 402 | N non-resident HIR block 403 | 404 | 405 | MISS 7 MISS 9 MISS 5 406 | ---------------------+-----+ -----------------+-----+ +-------------------+ 407 | | | v | | | 408 | v | | | v 409 | | H 9 + -| - - + 410 | H 7 | H 7 | | L 5 +--+ 411 | H 5 H 5 v N 5- + v H 9 | v 412 | L 3 L 3 L 3 N 7 | 413 | L 4 5 L 4 7 L 4 9 L 3 | 8 414 | L 8 1 L 8 5 L 8--+ 7 L 4 | 9 415 | +-------------------------------+ 416 | S Q S Q S Q S Q 417 | 418 | 419 | " 420 | (let [lirs (LIRSCache. {:1 1 :3 3 :4 4 :5 5 :8 8} 421 | {:5 11 :3 10 :4 9 :8 8} 422 | {:5 11 :1 10} 11 3 2)] 423 | (testing "miss 7 adds the block to lruS and lruQ and removes the oldest block in lruQ" 424 | (is (= (lirs-map (miss lirs :7 7)) 425 | {:cache {:3 3 :4 4 :5 5 :8 8 :7 7} 426 | :lruS {:7 12 :5 11 :3 10 :4 9 :8 8} 427 | :lruQ {:7 12 :5 11} 428 | :tick 12 :limitS 3 :limitQ 2}))) 429 | (testing "miss 9 makes 5 a non-resident HIR block" 430 | (is (= (lirs-map (-> lirs (miss :7 7) (miss :9 9))) 431 | {:cache {:3 3 :4 4 :8 8 :7 7 :9 9} 432 | :lruS {:9 13 :7 12 :5 11 :3 10 :4 9 :8 8} 433 | :lruQ {:9 13 :7 12} 434 | :tick 13 :limitS 3 :limitQ 2}))) 435 | (testing "miss 5, a non-resident HIR block becomes a new LIR block" 436 | (is (= (lirs-map (-> lirs (miss :7 7) (miss :9 9) (miss :5 5))) 437 | {:cache {:3 3 :4 4 :8 8 :9 9 :5 5} 438 | :lruS {:5 14 :9 13 :7 12 :3 10 :4 9} 439 | :lruQ {:8 14 :9 13} 440 | :tick 14 :limitS 3 :limitQ 2})))))) 441 | 442 | ;;;(deftest test-soft-cache-ilookup 443 | ;;; (testing "counts" 444 | ;;; (is (= 0 (count (soft-cache-factory {})))) 445 | ;;; (is (= 1 (count (soft-cache-factory {:a 1}))))) 446 | ;;; (testing "that the SoftCache can lookup via keywords" 447 | ;;; (do-ilookup-tests (soft-cache-factory small-map))) 448 | ;;; (testing "that the SoftCache can .lookup" 449 | ;;; (do-dot-lookup-tests (soft-cache-factory small-map))) 450 | ;;; (testing "that get and cascading gets work for SoftCache" 451 | ;;; (do-getting (soft-cache-factory big-map))) 452 | ;;; (testing "that finding works for SoftCache" 453 | ;;; (do-finding (soft-cache-factory small-map))) 454 | ;;; (testing "that contains? works for SoftCache" 455 | ;;; (do-contains (soft-cache-factory small-map)))) 456 | ;;; 457 | ;;;(deftest test-clear-soft-cache! 458 | ;;; (let [rq (ReferenceQueue.) 459 | ;;; ref (SoftReference. :bar rq) 460 | ;;; cache (doto (ConcurrentHashMap.) 461 | ;;; (.put :foo ref)) 462 | ;;; rcache (doto (ConcurrentHashMap.) 463 | ;;; (.put ref :foo)) 464 | ;;; _ (clear-soft-cache! cache rcache rq)] 465 | ;;; (is (contains? cache :foo) (str cache)) 466 | ;;; (is (contains? rcache ref) (str rcache)) 467 | ;;; (.clear ref) 468 | ;;; (.enqueue ref) 469 | ;;; (is (not (.get ref))) 470 | ;;; (let [_ (clear-soft-cache! cache rcache rq)] 471 | ;;; (is (not (contains? cache :foo))) 472 | ;;; (is (not (contains? rcache ref)))))) 473 | ;;; 474 | ;;;(deftest test-soft-cache 475 | ;;; (let [ref (atom nil) 476 | ;;; old-make-reference make-reference] 477 | ;;; (with-redefs [make-reference (fn [& args] 478 | ;;; (reset! ref (apply old-make-reference args)) 479 | ;;; @ref)] 480 | ;;; (let [old-soft-cache (soft-cache-factory {:foo1 :bar}) 481 | ;;; r @ref 482 | ;;; soft-cache (assoc old-soft-cache :foo2 :baz)] 483 | ;;; (is (and r (= :bar (.get r)))) 484 | ;;; (.clear r) 485 | ;;; (.enqueue r) 486 | ;;; (is (nil? (.lookup soft-cache :foo1))) 487 | ;;; (is (nil? (.lookup old-soft-cache :foo1))) 488 | ;;; (is (= :quux (.lookup soft-cache :foo1 :quux))) 489 | ;;; (is (= :quux (.lookup old-soft-cache :foo1 :quux))) 490 | ;;; (is (= :quux (.lookup soft-cache :foo3 :quux))) 491 | ;;; (is (= :quux (.lookup old-soft-cache :foo3 :quux))) 492 | ;;; (is (not (.has? soft-cache :foo1))) 493 | ;;; (is (not (.has? old-soft-cache :foo1))))))) 494 | ;;; 495 | ;;;(deftest test-soft-cache-eviction-handling 496 | ;;; (let [ref (atom nil) 497 | ;;; old-make-reference make-reference] 498 | ;;; (with-redefs [make-reference (fn [& args] 499 | ;;; (reset! ref (apply old-make-reference args)) 500 | ;;; @ref)] 501 | ;;; (let [cache (soft-cache-factory {})] 502 | ;;; (miss cache :foo "foo") 503 | ;;; (.enqueue @ref) 504 | ;;; (evict cache :foo))))) 505 | 506 | (deftest test-equiv 507 | (is (= (fifo-cache-factory {:a 1 :c 3} :threshold 3) 508 | (fifo-cache-factory {:a 1 :c 3} :threshold 3)))) 509 | 510 | (deftest test-persistent-cons 511 | (is (let [starts-with-a (fifo-cache-factory {:a 1} :threshold 3)] 512 | (= (fifo-cache-factory {:a 1 :c 3} :threshold 3) 513 | (conj starts-with-a [:c 3]) 514 | (conj starts-with-a {:c 3}))))) 515 | 516 | (deftest evict-with-object-exception 517 | (let [thing (proxy [Object] [] 518 | (Equals [obj] (throw (new Exception "Boom!"))))] ;;; equals 519 | (are [x y] (= x y) 520 | {:b 2} (-> (lru-cache-factory {:a thing, :b 2}) (evict :a) (.cache)) 521 | {:b 2} (-> (lu-cache-factory {:a thing, :b 2}) (evict :a) (.cache)) 522 | {:b 2} (-> (fifo-cache-factory {:a thing, :b 2}) (evict :a) (.cache))))) 523 | 524 | (deftest test-cache-iterable 525 | (let [c (fifo-cache-factory {:a 1 :b 2} :threshold 10)] 526 | (is (= #{:a :b} (set (iterator-seq (.GetEnumerator (keys c)))))))) ;;; .iterator 527 | 528 | (deftest test-fifo-miss-does-not-drop-ccache-39 529 | (let [c (fifo-cache-factory {:a 1 :b 2} :threshold 2)] 530 | (is (= #{:a :c} (set (-> c (evict :b) (miss :c 42) (.q))))) 531 | (is (= #{:c :d} (set (-> c (evict :b) (miss :c 42) (miss :d 43) (.q))))))) -------------------------------------------------------------------------------- /src/main/clojure/clojure/core/cache.clj: -------------------------------------------------------------------------------- 1 | ; Copyright (c) Rich Hickey. All rights reserved. 2 | ; The use and distribution terms for this software are covered by the 3 | ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) 4 | ; which can be found in the file epl-v10.html at the root of this distribution. 5 | ; By using this software in any fashion, you are agreeing to be bound by 6 | ; the terms of this license. 7 | ; You must not remove this notice, or any other, from this software. 8 | 9 | (ns ^{:doc "A caching library for Clojure." 10 | :author "Fogus"} 11 | clojure.core.cache 12 | (:require clojure.data.priority-map) 13 | (:import ;;; (java.lang.ref ReferenceQueue SoftReference) 14 | )) ;;; (java.util.concurrent ConcurrentHashMap) 15 | 16 | (set! *warn-on-reflection* true) 17 | 18 | ;; # Protocols and Types 19 | 20 | (defprotocol CacheProtocol 21 | "This is the protocol describing the basic cache capability." 22 | (lookup [cache e] 23 | [cache e not-found] 24 | "Retrieve the value associated with `e` if it exists, else `nil` in 25 | the 2-arg case. Retrieve the value associated with `e` if it exists, 26 | else `not-found` in the 3-arg case.") 27 | (has? [cache e] 28 | "Checks if the cache contains a value associated with `e`") 29 | (hit [cache e] 30 | "Is meant to be called if the cache is determined to contain a value 31 | associated with `e`") 32 | (miss [cache e ret] 33 | "Is meant to be called if the cache is determined to **not** contain a 34 | value associated with `e`") 35 | (evict [cache e] 36 | "Removes an entry from the cache") 37 | (seed [cache base] 38 | "Is used to signal that the cache should be created with a seed. 39 | The contract is that said cache should return an instance of its 40 | own type.")) 41 | 42 | (def ^{:private true} default-wrapper-fn #(%1 %2)) 43 | 44 | (defn through 45 | "The basic hit/miss logic for the cache system. Expects a wrap function and 46 | value function. The wrap function takes the value function and the item in question 47 | and is expected to run the value function with the item whenever a cache 48 | miss occurs. The intent is to hide any cache-specific cells from leaking 49 | into the cache logic itelf." 50 | ([cache item] (through default-wrapper-fn identity cache item)) 51 | ([value-fn cache item] (through default-wrapper-fn value-fn cache item)) 52 | ([wrap-fn value-fn cache item] 53 | (if (clojure.core.cache/has? cache item) 54 | (clojure.core.cache/hit cache item) 55 | (clojure.core.cache/miss cache item (wrap-fn #(value-fn %) item))))) 56 | 57 | (defn through-cache 58 | "The basic hit/miss logic for the cache system. Like through but always has 59 | the cache argument in the first position for easier use with swap! etc." 60 | ([cache item] (through-cache cache item default-wrapper-fn identity)) 61 | ([cache item value-fn] (through-cache cache item default-wrapper-fn value-fn)) 62 | ([cache item wrap-fn value-fn] 63 | (if (clojure.core.cache/has? cache item) 64 | (clojure.core.cache/hit cache item) 65 | (clojure.core.cache/miss cache item (wrap-fn #(value-fn %) item))))) 66 | 67 | (defmacro defcache 68 | [type-name fields & specifics] 69 | (let [[base & _] fields 70 | base-field (with-meta base {:tag 'clojure.lang.IPersistentMap})] 71 | `(deftype ~type-name [~@fields] 72 | ~@specifics 73 | 74 | clojure.lang.ILookup 75 | (valAt [this# key#] 76 | (lookup this# key#)) 77 | (valAt [this# key# not-found#] 78 | (if (has? this# key#) 79 | (lookup this# key#) 80 | not-found#)) 81 | 82 | System.Collections.IEnumerable ;;;java.lang.Iterable 83 | (System.Collections.IEnumerable.GetEnumerator [_#] ;;;(iterator [_#] 84 | (let [base# ^System.Collections.IEnumerable ~base-field] 85 | (.GetEnumerator ^System.Collections.IEnumerable base#))) ;;; (.iterator ~base-field)) 86 | 87 | clojure.lang.IPersistentMap 88 | (clojure.lang.IPersistentMap.assoc [this# k# v#] 89 | (miss this# k# v#)) 90 | (without [this# k#] 91 | (evict this# k#)) 92 | 93 | clojure.lang.Associative 94 | (containsKey [this# k#] 95 | (has? this# k#)) 96 | (entryAt [this# k#] 97 | (when (has? this# k#) 98 | (clojure.lang.MapEntry. k# (lookup this# k#)))) 99 | (clojure.lang.Associative.assoc [this# k# v#] ;;; had to add 100 | (miss this# k# v#)) 101 | 102 | 103 | clojure.lang.Counted 104 | (count [this#] 105 | (count ~base-field)) 106 | 107 | clojure.lang.IPersistentCollection 108 | (clojure.lang.IPersistentCollection.cons [this# elem#] 109 | (seed this# (conj ~base-field elem#))) 110 | (empty [this#] 111 | (seed this# (empty ~base-field))) 112 | (equiv [this# other#] 113 | (= other# ~base-field)) 114 | 115 | clojure.lang.Seqable 116 | (seq [_#] 117 | (seq ~base-field))))) 118 | 119 | (defcache BasicCache [cache] 120 | CacheProtocol 121 | (lookup [_ item] 122 | (get cache item)) 123 | (lookup [_ item not-found] 124 | (get cache item not-found)) 125 | (has? [_ item] 126 | (contains? cache item)) 127 | (hit [this item] this) 128 | (miss [_ item result] 129 | (BasicCache. (assoc cache item result))) 130 | (evict [_ key] 131 | (BasicCache. (dissoc cache key))) 132 | (seed [_ base] 133 | (BasicCache. base)) 134 | Object 135 | (ToString [_] (str cache))) ;;; ;;;toString 136 | 137 | ;; FnCache 138 | 139 | (defcache FnCache [cache f] 140 | CacheProtocol 141 | (lookup [_ item] 142 | (f (get cache item))) 143 | (lookup [_ item not-found] 144 | (let [ret (get cache item not-found)] 145 | (if (= not-found ret) 146 | not-found 147 | (f ret)))) 148 | (has? [_ item] 149 | (contains? cache item)) 150 | (hit [this item] this) 151 | (miss [_ item result] 152 | (BasicCache. (assoc cache item result))) 153 | (evict [_ key] 154 | (BasicCache. (dissoc cache key))) 155 | (seed [_ base] 156 | (BasicCache. base)) 157 | Object 158 | (ToString [_] (str cache))) ;;; ;;;toString 159 | 160 | ;; # FIFO 161 | 162 | (defn- describe-layout [mappy limit] 163 | (let [ks (keys mappy) 164 | [dropping keeping] (split-at (- (count ks) limit) ks)] 165 | {:dropping dropping 166 | :keeping keeping 167 | :queue 168 | (-> clojure.lang.PersistentQueue/EMPTY 169 | (into (repeat (- limit (count keeping)) ::free)) 170 | (into (take limit keeping)))})) 171 | 172 | (defn- prune-queue [q k] 173 | (reduce (fn [q e] (if (#{k} e) q (conj q e))) 174 | (conj clojure.lang.PersistentQueue/EMPTY ::free) 175 | q)) 176 | 177 | (defcache FIFOCache [cache q limit] 178 | CacheProtocol 179 | (lookup [_ item] 180 | (get cache item)) 181 | (lookup [_ item not-found] 182 | (get cache item not-found)) 183 | (has? [_ item] 184 | (contains? cache item)) 185 | (hit [this item] 186 | this) 187 | (miss [_ item result] 188 | (let [[kache qq] (let [k (peek q)] 189 | (if (>= (count cache) limit) 190 | [(dissoc cache k) (pop q)] 191 | [cache (pop q)]))] 192 | (FIFOCache. (assoc kache item result) 193 | (conj qq item) 194 | limit))) 195 | (evict [this key] 196 | (if (contains? cache key) 197 | (FIFOCache. (dissoc cache key) 198 | (prune-queue q key) 199 | limit) 200 | this)) 201 | (seed [_ base] 202 | (let [{dropping :dropping 203 | q :queue} (describe-layout base limit)] 204 | (FIFOCache. (apply dissoc base dropping) 205 | q 206 | limit))) 207 | Object 208 | (ToString [_] ;;; toString 209 | (str cache \, \space (pr-str q)))) 210 | 211 | (defn- build-leastness-queue 212 | [base start-at] 213 | (into (clojure.data.priority-map/priority-map) (for [[k _] base] [k start-at]))) 214 | 215 | (defcache LRUCache [cache lru tick limit] 216 | CacheProtocol 217 | (lookup [_ item] 218 | (get cache item)) 219 | (lookup [_ item not-found] 220 | (get cache item not-found)) 221 | (has? [_ item] 222 | (contains? cache item)) 223 | (hit [_ item] 224 | (let [tick+ (inc tick)] 225 | (LRUCache. cache 226 | (if (contains? cache item) 227 | (assoc lru item tick+) 228 | lru) 229 | tick+ 230 | limit))) 231 | (miss [_ item result] 232 | (let [tick+ (inc tick)] 233 | (if (>= (count lru) limit) 234 | (let [k (if (contains? lru item) 235 | item 236 | (first (peek lru))) ;; minimum-key, maybe evict case 237 | c (-> cache (dissoc k) (assoc item result)) 238 | l (-> lru (dissoc k) (assoc item tick+))] 239 | (LRUCache. c l tick+ limit)) 240 | (LRUCache. (assoc cache item result) ;; no change case 241 | (assoc lru item tick+) 242 | tick+ 243 | limit)))) 244 | (evict [this key] 245 | (if (contains? cache key) 246 | (LRUCache. (dissoc cache key) 247 | (dissoc lru key) 248 | (inc tick) 249 | limit) 250 | this)) 251 | (seed [_ base] 252 | (LRUCache. base 253 | (build-leastness-queue base 0) 254 | 0 255 | limit)) 256 | Object 257 | (ToString [_] ;;; toString 258 | (str cache \, \space lru \, \space tick \, \space limit))) 259 | 260 | 261 | (defn- key-killer-q 262 | [ttl q expiry now] 263 | (let [[ks q'] (reduce (fn [[ks q] [k g t]] 264 | (if (> (- now t) expiry) 265 | (if (= g (first (get ttl k))) 266 | [(conj ks k) (pop q)] 267 | [ks (pop q)]) 268 | (reduced [ks q]))) 269 | [[] q] 270 | q)] 271 | [#(apply dissoc % ks) q'])) 272 | 273 | (defcache TTLCacheQ [cache ttl q gen ttl-ms] 274 | CacheProtocol 275 | (lookup [this item] 276 | (let [ret (lookup this item ::nope)] 277 | (when-not (= ::nope ret) ret))) 278 | (lookup [this item not-found] 279 | (if (has? this item) 280 | (get cache item) 281 | not-found)) 282 | (has? [_ item] 283 | (and (let [[_ t] (get ttl item [0 (- ttl-ms)])] 284 | (< (- (Environment/TickCount) ;;; System/currentTimeMillis 285 | t) 286 | ttl-ms)) 287 | (contains? cache item))) 288 | (hit [this item] this) 289 | (miss [this item result] 290 | (let [now (Environment/TickCount) ;;; System/currentTimeMillis 291 | [kill-old q'] (key-killer-q ttl q ttl-ms now)] 292 | (TTLCacheQ. (assoc (kill-old cache) item result) 293 | (assoc (kill-old ttl) item [gen now]) 294 | (conj q' [item gen now]) 295 | (unchecked-inc gen) 296 | ttl-ms))) 297 | (seed [_ base] 298 | (let [now (Environment/TickCount)] ;;; System/currentTimeMillis 299 | (TTLCacheQ. base 300 | ;; we seed the cache all at gen, but subsequent entries 301 | ;; will get gen+1, gen+2 etc 302 | (into {} (for [x base] [(key x) [gen now]])) 303 | (into q (for [x base] [(key x) gen now])) 304 | (unchecked-inc gen) 305 | ttl-ms))) 306 | (evict [_ key] 307 | (TTLCacheQ. (dissoc cache key) 308 | (dissoc ttl key) 309 | q 310 | gen 311 | ttl-ms)) 312 | Object 313 | (ToString [_] ;;; toString 314 | (str cache \, \space ttl \, \space ttl-ms))) 315 | 316 | 317 | (defcache LUCache [cache lu limit] 318 | CacheProtocol 319 | (lookup [_ item] 320 | (get cache item)) 321 | (lookup [_ item not-found] 322 | (get cache item not-found)) 323 | (has? [_ item] 324 | (contains? cache item)) 325 | (hit [_ item] 326 | (LUCache. cache (update-in lu [item] inc) limit)) 327 | (miss [_ item result] 328 | (if (>= (count lu) limit) ;; need to evict? 329 | (let [min-key (if (contains? lu item) 330 | ::nope 331 | (first (peek lu))) ;; maybe evict case 332 | c (-> cache (dissoc min-key) (assoc item result)) 333 | l (-> lu (dissoc min-key) (update-in [item] (fnil inc 0)))] 334 | (LUCache. c l limit)) 335 | (LUCache. (assoc cache item result) ;; no change case 336 | (update-in lu [item] (fnil inc 0)) 337 | limit))) 338 | (evict [this key] 339 | (if (contains? this key) 340 | (LUCache. (dissoc cache key) 341 | (dissoc lu key) 342 | limit) 343 | this)) 344 | (seed [_ base] 345 | (LUCache. base 346 | (build-leastness-queue base 0) 347 | limit)) 348 | Object 349 | (ToString [_] ;;; toString 350 | (str cache \, \space lu \, \space limit))) 351 | 352 | 353 | ;; # LIRS 354 | ;; *initial Clojure implementation by Jan Oberhagemann* 355 | 356 | ;; A 357 | ;; [LIRS](http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.116.2184) 358 | ;; cache consists of two LRU lists, `S` and `Q`, and keeps more history 359 | ;; than a LRU cache. Every cached item is either a LIR, HIR or 360 | ;; non-resident HIR block. `Q` contains only HIR blocks, `S` contains 361 | ;; LIR, HIR, non-resident HIR blocks. The total cache size is 362 | ;; |`S`|+|`Q`|, |`S`| is typically 99% of the cache size. 363 | 364 | ;; * LIR block: 365 | ;; Low Inter-Reference block, a cached item with a short interval 366 | ;; between accesses. A block `x`, `x` ∈ `S` ∧ `x` ∉ `Q` ∧ `x` ∈ 367 | ;; `cache`, is a LIR block. 368 | 369 | ;; * HIR block: 370 | ;; High Inter-Reference block, a cached item with rare accesses and 371 | ;; long interval. A block `x`, `x` ∈ `Q` ∧ `x` ∈ `cache`, is a HIR block. 372 | 373 | ;; * non-resident HIR block: 374 | ;; only the key of the HIR block is cached, without the corresponding 375 | ;; value a test (has?) for the corresponding key is always a 376 | ;; miss. Used for additional history information. A block `x`, `x` ∈ 377 | ;; `S` ∧ `x` ∉ `Q` ∧ `x` ∉ `cache`, is a non-resident HIR block. 378 | 379 | ;; ## Outline of the implemented algorithm 380 | 381 | ;; `cache` is used to store the key value pairs. 382 | ;; `S` and `Q` maintain the relative order of accesses of the keys, like 383 | ;; a LRU list. 384 | 385 | ;; Definition of `prune stack`: 386 | ;; 387 | ;; repeatedly remove oldest item from S until an item k, k ∉ Q ∧ 388 | ;; k ∈ cache (a LIR block), is found 389 | 390 | 391 | ;; In case of a miss for key `k` and value `v` (`k` ∉ cache) and 392 | ;; 393 | ;; * (1.1) `S` is not filled, |`S`| < `limitS` 394 | ;; add k to S 395 | ;; add k to the cache 396 | 397 | ;; * (1.2) `k` ∉ `S`, never seen or not seen for a long, long time 398 | ;; remove oldest item x from Q 399 | ;; remove x from cache 400 | ;; add k to S 401 | ;; add k to Q 402 | ;; add k to the cache 403 | 404 | ;; * (1.3) `k` ∈ `S`, this is a non-resident HIR block 405 | ;; remove oldest item x from Q 406 | ;; remove x from cache 407 | ;; add k to S 408 | ;; remove oldest item y from S 409 | ;; add y to Q 410 | ;; prune stack 411 | 412 | 413 | ;; In case of a hit for key `k` (`k` ∈ cache) and 414 | 415 | ;; * (2.1) `k` ∈ `S` ∧ `k` ∉ `Q`, a LIR block 416 | ;; add k to S / refresh 417 | ;; prune stack if k was the oldest item in S 418 | 419 | ;; * (2.2) `k` ∈ `S` ∧ `k` ∈ `Q`, a HIR block 420 | ;; add k to S / refresh 421 | ;; remove k from Q 422 | ;; remove oldest item x from S 423 | ;; add x to Q 424 | ;; prune stack 425 | 426 | ;; * (2.3) `k` ∉ `S` ∧ `k` ∈ `Q`, a HIR block, only older than the oldest item in S 427 | ;; add k to S 428 | ;; add k to Q / refresh 429 | 430 | (defn- prune-stack [lruS lruQ cache] 431 | (loop [s lruS q lruQ c cache] 432 | (let [k (apply min-key s (keys s))] 433 | (if (or (contains? q k) ; HIR item 434 | (not (contains? c k))) ; non-resident HIR item 435 | (recur (dissoc s k) q c) 436 | s)))) 437 | 438 | (defcache LIRSCache [cache lruS lruQ tick limitS limitQ] 439 | CacheProtocol 440 | (lookup [_ item] 441 | (get cache item)) 442 | (lookup [_ item not-found] 443 | (get cache item not-found)) 444 | (has? [_ item] 445 | (contains? cache item)) 446 | (hit [_ item] 447 | (let [tick+ (inc tick)] 448 | (if (not (contains? lruS item)) 449 | ; (2.3) item ∉ S ∧ item ∈ Q 450 | (LIRSCache. cache (assoc lruS item tick+) (assoc lruQ item tick+) tick+ limitS limitQ) 451 | (let [k (apply min-key lruS (keys lruS))] 452 | (if (contains? lruQ item) 453 | ; (2.2) item ∈ S ∧ item ∈ Q 454 | (let [new-lruQ (-> lruQ (dissoc item) (assoc k tick+))] 455 | (LIRSCache. cache 456 | (-> lruS (dissoc k) (assoc item tick+) (prune-stack new-lruQ cache)) 457 | new-lruQ 458 | tick+ 459 | limitS 460 | limitQ)) 461 | ; (2.1) item ∈ S ∧ item ∉ Q 462 | (LIRSCache. cache 463 | (-> lruS (assoc item tick+) (prune-stack lruQ cache)) 464 | lruQ 465 | tick+ 466 | limitS 467 | limitQ)))))) 468 | 469 | (miss [_ item result] 470 | (let [tick+ (inc tick)] 471 | (if (< (count cache) limitS) 472 | ; (1.1) 473 | (let [k (apply min-key lruS (keys lruS))] 474 | (LIRSCache. (assoc cache item result) 475 | (-> lruS (dissoc k) (assoc item tick+)) 476 | lruQ 477 | tick+ 478 | limitS 479 | limitQ)) 480 | (let [k (apply min-key lruQ (keys lruQ)) 481 | new-lruQ (dissoc lruQ k) 482 | new-cache (-> cache (dissoc k) (assoc item result))] 483 | (if (contains? lruS item) 484 | ; (1.3) 485 | (let [lastS (apply min-key lruS (keys lruS))] 486 | (LIRSCache. new-cache 487 | (-> lruS (dissoc lastS) (assoc item tick+) (prune-stack new-lruQ new-cache)) 488 | (assoc new-lruQ lastS tick+) 489 | tick+ 490 | limitS 491 | limitQ)) 492 | ; (1.2) 493 | (LIRSCache. new-cache 494 | (assoc lruS item tick+) 495 | (assoc new-lruQ item tick+) 496 | tick+ 497 | limitS 498 | limitQ)))))) 499 | (seed [_ base] 500 | (LIRSCache. base 501 | (into {} (for [x (range (- limitS) 0)] [x x])) 502 | (into {} (for [x (range (- limitQ) 0)] [x x])) 503 | 0 504 | limitS 505 | limitQ)) 506 | Object 507 | (ToString [_] ;;; toString 508 | (str cache \, \space lruS \, \space lruQ \, \space tick \, \space limitS \, \space limitQ))) 509 | ;;; Port SoftCache some other time -- TODO 510 | ;;;(defn clear-soft-cache! [^java.util.Map cache ^java.util.Map rcache ^ReferenceQueue rq] 511 | ;;; (loop [r (.poll rq)] 512 | ;;; (when r 513 | ;;; (when-let [item (get rcache r)] 514 | ;;; (.remove cache item)) 515 | ;;; (.remove rcache r) 516 | ;;; (recur (.poll rq))))) 517 | ;;; 518 | ;;;(defn make-reference [v rq] 519 | ;;; (if (nil? v) 520 | ;;; (SoftReference. ::nil rq) 521 | ;;; (SoftReference. v rq))) 522 | ;;; 523 | ;;;(defcache SoftCache [^java.util.Map cache ^java.util.Map rcache rq] 524 | ;;; CacheProtocol 525 | ;;; (lookup [_ item] 526 | ;;; (when-let [^SoftReference r (get cache (or item ::nil))] 527 | ;;; (let [v (.get r)] 528 | ;;; (if (= ::nil v) 529 | ;;; nil 530 | ;;; v)))) 531 | ;;; (lookup [_ item not-found] 532 | ;;; (if-let [^SoftReference r (get cache (or item ::nil))] 533 | ;;; (if-let [v (.get r)] 534 | ;;; (if (= ::nil v) 535 | ;;; nil 536 | ;;; v) 537 | ;;; not-found) 538 | ;;; not-found)) 539 | ;;; (has? [_ item] 540 | ;;; (let [item (or item ::nil) 541 | ;;; ^SoftReference cell (get cache item)] 542 | ;;; (boolean 543 | ;;; (when cell 544 | ;;; (not (nil? (.get cell))))))) 545 | ;;; (hit [this item] 546 | ;;; (clear-soft-cache! cache rcache rq) 547 | ;;; this) 548 | ;;; (miss [this item result] 549 | ;;; (let [item (or item ::nil) 550 | ;;; r (make-reference result rq)] 551 | ;;; (.put cache item r) 552 | ;;; (.put rcache r item) 553 | ;;; (clear-soft-cache! cache rcache rq) 554 | ;;; this)) 555 | ;;; (evict [this key] 556 | ;;; (let [key (or key ::nil) 557 | ;;; r (get cache key)] 558 | ;;; (when r 559 | ;;; (.remove cache key) 560 | ;;; (.remove rcache r)) 561 | ;;; (clear-soft-cache! cache rcache rq) 562 | ;;; this)) 563 | ;;; (seed [_ base] 564 | ;;; (let [soft-cache? (instance? SoftCache base) 565 | ;;; cache (ConcurrentHashMap.) 566 | ;;; rcache (ConcurrentHashMap.) 567 | ;;; rq (ReferenceQueue.)] 568 | ;;; (if (seq base) 569 | ;;; (doseq [[k ^SoftReference v] base] 570 | ;;; (let [k (or k ::nil) 571 | ;;; r (if soft-cache? 572 | ;;; (make-reference (.get v) rq) 573 | ;;; (make-reference v rq))] 574 | ;;; (.put cache k r) 575 | ;;; (.put rcache r k)))) 576 | ;;; (SoftCache. cache rcache rq))) 577 | ;;; Object 578 | ;;; (toString [_] (str cache))) 579 | 580 | ;; Factories 581 | 582 | (defn basic-cache-factory 583 | "Returns a pluggable basic cache initialized to `base`" 584 | [base] 585 | {:pre [(map? base)]} 586 | (BasicCache. base)) 587 | 588 | (defn fifo-cache-factory 589 | "Returns a FIFO cache with the cache and FIFO queue initialized to `base` -- 590 | the queue is filled as the values are pulled out of `base`. If the associative 591 | structure can guarantee ordering, then the said ordering will define the 592 | eventual eviction order. Otherwise, there are no guarantees for the eventual 593 | eviction ordering. 594 | 595 | This function takes an optional `:threshold` argument that defines the maximum number 596 | of elements in the cache before the FIFO semantics apply (default is 32). 597 | 598 | If the number of elements in `base` is greater than the limit then some items 599 | in `base` will be dropped from the resulting cache. If the associative 600 | structure used as `base` can guarantee sorting, then the last `limit` elements 601 | will be used as the cache seed values. Otherwise, there are no guarantees about 602 | the elements in the resulting cache." 603 | [base & {threshold :threshold :or {threshold 32}}] 604 | {:pre [(number? threshold) (< 0 threshold) 605 | (map? base)] 606 | :post [(== threshold (count (.q ^FIFOCache %)))]} 607 | (clojure.core.cache/seed (FIFOCache. {} clojure.lang.PersistentQueue/EMPTY threshold) base)) 608 | 609 | (defn lru-cache-factory 610 | "Returns an LRU cache with the cache and usage-table initialized to `base` -- 611 | each entry is initialized with the same usage value. 612 | 613 | This function takes an optional `:threshold` argument that defines the maximum number 614 | of elements in the cache before the LRU semantics apply (default is 32)." 615 | [base & {threshold :threshold :or {threshold 32}}] 616 | {:pre [(number? threshold) (< 0 threshold) 617 | (map? base)]} 618 | (clojure.core.cache/seed (LRUCache. {} (clojure.data.priority-map/priority-map) 0 threshold) base)) 619 | 620 | (defn ttl-cache-factory 621 | "Returns a TTL cache with the cache and expiration-table initialized to `base` -- 622 | each with the same time-to-live. 623 | 624 | This function also allows an optional `:ttl` argument that defines the default 625 | time in milliseconds that entries are allowed to reside in the cache." 626 | [base & {ttl :ttl :or {ttl 2000}}] 627 | {:pre [(number? ttl) (<= 0 ttl) 628 | (map? base)]} 629 | (clojure.core.cache/seed (TTLCacheQ. {} {} clojure.lang.PersistentQueue/EMPTY 0 ttl) base)) 630 | 631 | (defn lu-cache-factory 632 | "Returns an LU cache with the cache and usage-table initialized to `base`. 633 | 634 | This function takes an optional `:threshold` argument that defines the maximum number 635 | of elements in the cache before the LU semantics apply (default is 32)." 636 | [base & {threshold :threshold :or {threshold 32}}] 637 | {:pre [(number? threshold) (< 0 threshold) 638 | (map? base)]} 639 | (clojure.core.cache/seed (LUCache. {} (clojure.data.priority-map/priority-map) threshold) base)) 640 | 641 | (defn lirs-cache-factory 642 | "Returns an LIRS cache with the S & R LRU lists set to the indicated 643 | limits." 644 | [base & {:keys [s-history-limit q-history-limit] 645 | :or {s-history-limit 32 646 | q-history-limit 32}}] 647 | {:pre [(number? s-history-limit) (< 0 s-history-limit) 648 | (number? q-history-limit) (< 0 q-history-limit) 649 | (map? base)]} 650 | (clojure.core.cache/seed (LIRSCache. {} {} {} 0 s-history-limit q-history-limit) base)) 651 | 652 | (defn soft-cache-factory 653 | "Returns a SoftReference cache. Cached values will be referred to with 654 | SoftReferences, allowing the values to be garbage collected when there is 655 | memory pressure on the JVM. 656 | 657 | SoftCache is a mutable cache, since it is always based on a 658 | ConcurrentHashMap." 659 | [base] 660 | {:pre [(map? base)]} 661 | (throw (System.NotImplementedException.)) ;;; (clojure.core.cache/seed (SoftCache. (ConcurrentHashMap.) (ConcurrentHashMap.) (ReferenceQueue.)) 662 | ) ;;; base) 663 | --------------------------------------------------------------------------------