pax_global_header00006660000000000000000000000064136441556200014520gustar00rootroot0000000000000052 comment=d674ba6151cef457e793984fb896799c67df808c core.cache-core.cache-1.0.207/000077500000000000000000000000001364415562000156515ustar00rootroot00000000000000core.cache-core.cache-1.0.207/.github/000077500000000000000000000000001364415562000172115ustar00rootroot00000000000000core.cache-core.cache-1.0.207/.github/PULL_REQUEST_TEMPLATE000066400000000000000000000013011364415562000224060ustar00rootroot00000000000000Hi! Thanks for your interest in contributing to this project. Clojure contrib projects do not use GitHub issues or pull requests, and require a signed Contributor Agreement. If you would like to contribute, please read more about the CA and sign that first (this can be done online). Then go to this project's issue tracker in JIRA to create tickets, update tickets, or submit patches. For help in creating tickets and patches, please see: - Signing the CA: https://clojure.org/community/contributing - Creating Tickets: https://clojure.org/community/creating_tickets - Developing Patches: https://clojure.org/community/developing_patches - Contributing FAQ: https://clojure.org/community/contributing core.cache-core.cache-1.0.207/.gitignore000066400000000000000000000001041364415562000176340ustar00rootroot00000000000000target .lein* lib multi-lib .nrepl-port .idea .cpcache/ /build.boot core.cache-core.cache-1.0.207/CONTRIBUTING.md000066400000000000000000000007371364415562000201110ustar00rootroot00000000000000This is a [Clojure contrib] project. Under the Clojure contrib [guidelines], this project cannot accept pull requests. All patches must be submitted via [JIRA]. See [Contributing] on the Clojure website for more information on how to contribute. [Clojure contrib]: https://clojure.org/community/contrib_libs [Contributing]: https://clojure.org/community/contributing [JIRA]: http://clojure.atlassian.net/browse/CCACHE [guidelines]: https://clojure.org/community/contrib_howto core.cache-core.cache-1.0.207/README.md000066400000000000000000000216311364415562000171330ustar00rootroot00000000000000clojure.core.cache ======================================== core.cache is a Clojure contrib library providing the following features: * An underlying `CacheProtocol` used as the base abstraction for implementing new synchronous caches * A `defcache` macro for hooking your `CacheProtocol` implementations into the Clojure associative data capabilities. * Implementations of some basic caching strategies - First-in-first-out (FIFOCache) - Least-recently-used (LRUCache) - Least-used (LUCache -- sometimes called Least Frequently Used) - Time-to-live (TTLCacheQ) - Naive cache (BasicCache) - Naive cache backed with soft references (SoftCache) * Implementation of an efficient buffer replacement policy based on the *low inter-reference recency set* algorithm (LIRSCache) described in the [LIRS](http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.116.2184) paper * Factory functions for each existing cache type * Caches are generally immutable and should be used in conjunction with Clojure's state management, such as `atom`. SoftCache is the exception here, built on top of mutable Java collections, but it can be treated as an immutable cache as well. The `clojure.core.cache` namespace contains the immutable caches themselves. The `clojure.core.cache.wrapped` namespace contains the same API operating on caches wrapped in atoms, which is the "normal" use in the wild (introduced in 0.8.0). core.cache is based on an old library named Clache that has been thoroughly deprecated. Releases and Dependency Information ======================================== This project follows the version scheme MAJOR.MINOR.COMMITS where MAJOR and MINOR provide some relative indication of the size of the change, but do not follow semantic versioning. In general, all changes endeavor to be non-breaking (by moving to new names rather than by breaking existing names). COMMITS is an ever-increasing counter of commits since the beginning of this repository. Latest stable release: 1.0.207 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22core.cache%22) * [Development Snapshot Versions](https://oss.sonatype.org/index.html#nexus-search;gav~org.clojure~core.cache~~~) [Leiningen](https://github.com/technomancy/leiningen) dependency information: [org.clojure/core.cache "1.0.207"] [Maven](http://maven.apache.org/) dependency information: org.clojure core.cache 1.0.207 Example Usage ======================================== ```clojure (require '[clojure.core.cache :as cache]) (def C1 (cache/fifo-cache-factory {:a 1, :b 2})) (def C1' (if (cache/has? C1 :c) (cache/hit C1 :c) (cache/miss C1 :c 42))) ;=> {:a 1, :b 2, :c 42} (cache/lookup C1' :c) ;=> 42 (get C1' :c) ; cache/lookup is implemented as get ;=> 42 ;; a shorthand for the above conditional... (def C1' (cache/through-cache C1 :c (constantly 42))) ;; ...which uses a value to compute the result from the key... (cache/through-cache C1 my-key (partial jdbc/get-by-id db-spec :storage)) ;; ...so you could fetch values from a database if they're not in cache... (cache/evict C1 :b) ;=> {:a 1} ;; since the caches are immutable, you would normally wrap them in an atom (def C2 (atom (cache/fifo-cache-factory {:a 1, :b 2}))) (swap! C2 cache/through-cache :d (constantly 13)) ;=> {:a 1, :b 3, :d 13} (swap! C2 cache/evict :b) ;=> {:a 1, :d 13} (get @C2 :a) ;=> 1 ;; or use the wrapped API instead: (require '[clojure.core.cache.wrapped :as c]) (def C3 (c/fifo-cache-factory {:a 1, :b 2})) (c/through-cache C3 :d (constantly 13)) ; returns updated cache ;=> {:a 1, :b 3, :d 13} (c/evict C3 :b) ;=> {:a 1, :d 13} (c/lookup C3 :a) ; or (get @C3 :a) ;=> 1 ;; unique to the wrapped API: (c/lookup-or-miss C3 :b (constantly 42)) ;=> 42 @C3 ;=> {:a 1, :d 13, :b 42} ``` Refer to docstrings in the `clojure.core.cache` or `clojure.core.cache.wrapped` namespaces, or the [autogenerated API documentation](http://clojure.github.com/core.cache/) for additional documentation. Developer Information ======================================== * [GitHub project](https://github.com/clojure/core.cache) * [Bug Tracker](http://clojure.atlassian.net/browse/CCACHE) * [Continuous Integration](http://build.clojure.org/job/core.cache/) * [Compatibility Test Matrix](http://build.clojure.org/job/core.cache-test-matrix/) Change Log ==================== * Release 1.0.207 on 2020-04-10 * Switch to 1.0.x versioning. * Update `data.priority-map` to 1.0.0 * Release 0.8.2 on 2019-09-30 * [CCACHE-57](http://clojure.atlassian.net/browse/CCACHE-57) Fix wrapped cache `miss` function * Release 0.8.1 on 2019-08-24 * [CCACHE-56](http://clojure.atlassian.net/browse/CCACHE-56) Fix wrapped TTL cache and fix `clojure.core.cache.wrapped/lookup-or-miss` for caches that can invalidate on `lookup` * Release 0.8.0 on 2019-08-24 * [CCACHE-50](http://clojure.atlassian.net/browse/CCACHE-50) Add `clojure.core.cache.wrapped` namespace with atom-wrapped caches for a more convenient API that adds `lookup-or-miss` which avoids the possibility of cache stampede * Release 0.7.2 on 2019-01-06 * [CCACHE-53](http://clojure.atlassian.net/browse/CCACHE-53) Remove unnecessary/additional `.get` call (Neil Prosser) * [CCACHE-52](http://clojure.atlassian.net/browse/CCACHE-52) Fix NPE in SoftCache (Neil Prosser) * Release 0.7.1 on 2018.03.02 * [CCACHE-49](http://clojure.atlassian.net/browse/CCACHE-49) Fix TTLCacheQ `seed` function and expand tests on TTLCacheQ * Release 0.7.0 on 2018.03.01 * [CCACHE-46](http://clojure.atlassian.net/browse/CCACHE-46) Fix TTLCache when wrapped around another cache (Ivan Kryvoruchko) * [CCACHE-43](http://clojure.atlassian.net/browse/CCACHE-43) Add `through-cache` to provide a version of `through` that plays nice with `swap!` etc * [CCACHE-40](http://clojure.atlassian.net/browse/CCACHE-40) Fix FIFOCache stack overflow on large threshold (uses PersistentQueue now instead of concat and list) * [CCACHE-39](http://clojure.atlassian.net/browse/CCACHE-39) Fix FIFOCache evict/miss queue handling * [CCACHE-20](http://clojure.atlassian.net/browse/CCACHE-20) Updated README to clarify that caches are immutable and provide examples of use with `atom` etc * [CCACHE-15](http://clojure.atlassian.net/browse/CCACHE-15) Added queue and generation logic to reduce `miss` cost and make `evict` O(1); rename TTLCache -> TTLCacheQ (Kevin Downey) * Drop support for Clojure 1.3/1.4/1.5 * Release 0.6.5 on 2016.03.28 * Bump tools.priority-map dependency to 0.0.7 * [CCACHE-41](http://clojure.atlassian.net/browse/CCACHE-41) Implement Iterable in defcache * [CCACHE-44](http://clojure.atlassian.net/browse/CCACHE-44) Avoid equals comparison on cache miss * [CCACHE-37](http://clojure.atlassian.net/browse/CCACHE-37) Fix typo in docstring * Release 0.6.4 on 2014.08.06 * Thanks to Paul Stadig and Nicola Mometto who contributed patches for this release * [CCACHE-34](http://clojure.atlassian.net/browse/CCACHE-34) bump tools.priority-map dependency to 0.0.4 * [CCACHE-28](http://clojure.atlassian.net/browse/CCACHE-28) concurrency bug in has? for SoftCache * [CCACHE-29](http://clojure.atlassian.net/browse/CCACHE-29) fix conj implementation for caches * [CCACHE-30](http://clojure.atlassian.net/browse/CCACHE-30) make-reference need not be dynamic * [CCACHE-26](http://clojure.atlassian.net/browse/CCACHE-26) hit function in LRU cache can give funny results * Release 0.6.3 on 2013.03.15 * Added through to encapsulate check logic * Release 0.6.2 on 2012.08.07 [more information](http://blog.fogus.me/?p=4527) * Removed reflection warnings * Fixed eviction of items from LU, TTL and LRU caches with thresholds less than two * Fixed eviction of items from FIFO cache prior to threshold * Release 0.6.2 on 2012.07.13 [more information](http://blog.fogus.me/2012/07/13/announcing-core-cache-version-0-6-1/) * Added SoftCache * Fixed eviction of items from LU and LRU caches prior to threshold * Adjusted default thresholds in factory functions * Release 0.5.0 on 2011.12.13 [more information](http://blog.fogus.me/2011/12/13/announcing-core-cache-v0-5-0/) * Added `evict` * Added cache factory functions * Added associatve operation support Copyright and License ======================================== Copyright (c) Rich Hickey, Michael Fogus and contributors, 2012-2020. 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. core.cache-core.cache-1.0.207/deps.edn000066400000000000000000000023271364415562000173000ustar00rootroot00000000000000;; You can run clojure.core.cache tests with: clj -A:test:runner ;; You can also specify an alias to select which version of Clojure to test ;; against: :1.6 :1.7 :1.8 :1.9 :1.10 :master {:paths ["src/main/clojure"] :deps {org.clojure/data.priority-map {:mvn/version "1.0.0"}} :aliases {:test {:extra-paths ["src/test/clojure"] :extra-deps {org.clojure/test.check {:mvn/version "1.0.0"}}} :1.6 {:override-deps {org.clojure/clojure {:mvn/version "1.6.0"}}} :1.7 {:override-deps {org.clojure/clojure {:mvn/version "1.7.0"}}} :1.8 {:override-deps {org.clojure/clojure {:mvn/version "1.8.0"}}} :1.9 {:override-deps {org.clojure/clojure {:mvn/version "1.9.0"}}} :1.10 {:override-deps {org.clojure/clojure {:mvn/version "1.10.1"}}} :master {:override-deps {org.clojure/clojure {:mvn/version "1.11.0-master-SNAPSHOT"}}} :runner {:extra-deps {com.cognitect/test-runner {:git/url "https://github.com/cognitect-labs/test-runner" :sha "f7ef16dc3b8332b0d77bc0274578ad5270fbfedd"}} :main-opts ["-m" "cognitect.test-runner" "-d" "src/test/clojure"]}}} core.cache-core.cache-1.0.207/docs/000077500000000000000000000000001364415562000166015ustar00rootroot00000000000000core.cache-core.cache-1.0.207/docs/Building.md000066400000000000000000000011661364415562000206640ustar00rootroot00000000000000Building core.cache =================== 1. Clone the [core.cache git repository](http://github.com/clojure/core.cache) or download its [source archive](https://github.com/clojure/core.cache/zipball/master) 2. Run `mvn package` to generate a Jar file 3. Run `mvn install` to install the Jar into your local Maven repository To test that the build succeeded try: mvn clojure:repl This will launch a Clojure REPL. Try the following to exercise core.cache: ```clojure (use 'clojure.core.cache) (def c (fifo-cache-factory 1 {:a 42})) (-> c (assoc :b 1) (assoc :z 108)) ``` You should see the result `{:z 108}`. core.cache-core.cache-1.0.207/docs/Composing.md000066400000000000000000000020451364415562000210620ustar00rootroot00000000000000Because core.cache types are defined in terms of the `CacheProtocol` protocol and the cache functions adhere to its strictures, any cache types can serve as the basis for another. Put in simpler terms, to create a cache instance composed of the seed data `{:a 1, :b 2}` with a FIFO eviction policy and a 5-second entry lifetime, then the following nested cache usage would work: ```clojure (def C (-> {:a 1 :b 2} (fifo-cache-factory :threshold 2) (ttl-cache-factory :ttl 5000))) ;; used right away (assoc C :c 42) ;;=> {:b 2, :c 42} ;; used after 5 seconds (assoc C :d 138) ;;=> {:d 138} ``` What the code above does is to simply use a `FIFOCache` instance, seeded with `{:a 1, :b 2}` as the seed for a `TTLCacheQ` instance. As shown, within the TTL window, the cache evicts its elements using a FIFO policy. However, once a TTL window has expired the expired elements are also evicted. core.cache-core.cache-1.0.207/docs/Extending.md000066400000000000000000000114531364415562000210540ustar00rootroot00000000000000Creating custom caches ====================== This page will guide you through the steps required to create your own custom cache types. In this tutorial you will create a naive cache type `LameCache` with a very straight-forward and illustrative eviction policy. The details of the implementation are as follows: * `LameCache` should work like a map * Its eviction policy is semi-random * It allows a threshold CacheProtocol ------------- The best place to start when attempting to create your own cache implementations with core.cache is with the `CacheProtocol`: ```clojure (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.")) ``` The commentary on the cache protocol is fairly straight-forward, but there are subtlties in play that I will discuss herein. The defcache convenience macro ------------------------------ The core.cache library provides a convenience macro for defining cache implementations called `defcache`. The advantage that `defcache` provides is that by implementing the `CacheProtocol` protocol your caches will automatically implement Clojure's associative data structure protocols as well. The `defcache` does this by implementing the associative behaviors in terms of the `CacheProtocol`. *All caveats apply regarding the [proper usage patterns](./Using.md).* Implementing a custom cache --------------------------- Therefore, to implement a version of `LameCache`, the `defcache` usage is as follows: ```clojure (defcache LameCache [cache ks threshold] CacheProtocol ``` The first step is to name the type and to provide its attributes: * `cache`: The base storage structure - Should be an associative structure - **Must** be the first attribute listed * `ks`: A set of keys stored * `threshold`: The threshold defining the point when eviction policies take effect ```clojure (lookup [_ item] (get cache item)) (lookup [_ item not-found] (get cache item not-found)) ``` The `lookup` method is straight-forward. Simply retrieve the item at the given key from the base `cache`. ```clojure (has? [_ item] (contains? cache item)) ``` The `has?` method is likewise straight-forward. Simply return `true` if a key is located in the base `cache`; `false` otherwise. ```clojure (hit [this item] this) ``` The `hit` method in this case is trivial, it just returns the instance itself. If your cache implementation needs to track hit history then you would probably return a new instance with history updated. ```clojure (miss [_ item result] (let [size (count cache)] (if (<= size threshold) (LameCache. (assoc cache item result) (conj ks item) threshold) (let [new-cache (dissoc cache (first ks)) new-keys (dissoc ks item)] (LameCache. (assoc new-cache item result) (conj item new-keys) threshold))))) ``` The `miss` method is where all the action takes place. That is, if the size of the base `cache` is less than the `threshold` then the cached value is stored in the base `cache` and its key in the `ks` set. However, if the threshold was breached then the first key in the `ks` set is removed from the base `cache` and `ks` and a new `LameCache` instance is returned with the new key and value added to `cache` and `ks`. ```clojure (evict [_ key] (LameCache. (dissoc cache key) (dissoc ks key) threshold)) ``` The `evict` method purges the value from the base `cache` and its key from `ks`, returning a new `LameCache` instance. ```clojure (seed [_ base] (LameCache. base (set (keys base)) threshold)) ``` The `seed` function is meant to populate the cache with a set of known values. For `LameCache` the seed forms the base `cache` and its keys the `ks`. Seeding a cache is often a delicate matter and your custom caches may require some thought. ```clojure Object (toString [_] (str cache))) ``` Finally, `LameCache` is given a lame `toString` method. core.cache-core.cache-1.0.207/docs/FIFO.md000066400000000000000000000052321364415562000176500ustar00rootroot00000000000000# FIFO cache A First-In-First-Out cache is one that uses queuing logic for its backing store, expunging the elements at the front of the queue when a predetermined threshold is exceeded. > In simple terms, the FIFO cache will remove the element that has been in the cache the longest. *Before reading this page please make sure that you've read and understand the [Basic Usage patterns](./Using.md).* ## General use To create a core.cache `FIFOCache` instance you should *always* use its associated constructor function `fifo-cache-factory` with an optional `:threshold` parameter: ```clojure (ns your.lib (:require [clojure.core.cache :as cache])) (def C (cache/fifo-cache-factory {:a 1, :b 2, :c 3} :threshold 3)) ``` *note: the default `:threshold` value is 32* The cache instance `C` is initialized with the seed map `{:a 1, :b 2}` and a queue threshold of `3`, For your own purposes `2` is probably too small, but it's fine for the purpose of illustration. Since the queue threshold was set to `3` adding one more element should evict the first element added `:a`; and indeed it does: ```clojure (assoc C :d 42) ;=> {:c 3, :b 2, :d 42} ``` Likewise, adding two more elements should evict two values: ```clojure (assoc C :x 36 :z 138) ;=> {:z 138, :x 36, :b 2} ``` Like all of the implementations in core.cache, `FIFOCache` instances operate like regular maps and are immutable. All caveats apply regarding the [proper usage patterns](./Using.md). ## FIFO cache use cases The FIFO cache eviction policy is very simple to implement and understand. Additionally, because the policy requires very little information, the implementation is reasonably efficient. The FIFO eviction policy is the base-level caching capability and is generally applicable. However, because of its broad applicability it tends to evict at a rate non-optimally for every scenario. Having said that, there are a few reasons why you might want to use a FIFO cache. ### Benefits to using a FIFO cache * Its logic is easy to understand * It's reasonably fast * It's reasonably lightweight * Even a naive cache eviction policy may prove better than none * Your expensive calculations tend toward single-use * It works well for data subject to sequentiality ### Disadvantages to using a FIFO cache * It's not efficient for data subject to locality concerns * Increasing the cache size does not benefit its efficiency (see [Bélády's anomaly](http://en.wikipedia.org/wiki/B%C3%A9l%C3%A1dy's_anomaly)) As always, you should measure your system's characteristics to determine the best eviction strategy for your purposes.core.cache-core.cache-1.0.207/docs/Including.md000066400000000000000000000017111364415562000210370ustar00rootroot00000000000000Including core.cache in your projects ===================================== The core.cache releases and snapshots are stored in the following repositories: * Release versions stored at [Maven Central](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22core.cache%22) * Snapshot versions stored at [Sonatype](https://oss.sonatype.org/index.html#nexus-search;gav~org.clojure~core.cache~~~) (url at ) ## Leiningen You can use core.cache in your [Leiningen](https://github.com/technomancy/leiningen) projects with the following `:dependencies` directive in your `project.clj` file: [org.clojure/core.cache "1.0.207"] ## Maven For Maven-driven projects, use the following slice of XML in your `pom.xml`'s `` section: org.clojure core.cache 1.0.207 Enjoy! core.cache-core.cache-1.0.207/docs/LIRS.md000066400000000000000000000020211364415562000176670ustar00rootroot00000000000000LIRS cache ========== The low inter-reference recency set cache is one that, like [LRU](./LRU.md), uses recency as its basis for behavior. Unlike, LRU however, LIRS uses access recency of other cache elements relative to any other block to determine its eviction policy. *Before reading this page please make sure that you've read and understand the [Basic Usage patterns](./Using.md).* General usage ------------- To create a core.cache `LRUCache` instance you can do the following: ```clojure (ns your.lib (:require [clojure.core.cache :as cache])) (def C (cache/lirs-cache-factory {})) ``` Most of the trival examples will likely look very similar to the examples found in the [LRU](./LRU.md) page. See the discussion in the next section why you might wish to choose LIRS instead. Like all of the implementations in core.cache, `LRUCache` instances operate like regular maps and are immutable. All caveats apply regarding the [proper usage patterns](./Using.md). LIRS cache use cases -------------------- TODO core.cache-core.cache-1.0.207/docs/LRU.md000066400000000000000000000055651364415562000176000ustar00rootroot00000000000000LRU cache ========== The least-recently-used cache is one that evicts items that are accessed least frequently once its threshold has been exceeded. > In simple terms, the LRU cache will remove the element in the cache that has not been accessed in the longest time. *Before reading this page please make sure that you've read and understand the [Basic Usage patterns](./Using.md).* General usage ------------- To create a core.cache `LRUCache` instance you should *always* use its associated constructor function `lru-cache-factory` with an optional `:threshold` parameter: ```clojure (ns your.lib (:require [clojure.core.cache :as cache])) (def C (cache/lru-cache-factory {} :threshold 2)) (-> C (assoc :a 1) (assoc :b 2)) ;=> {:a 1, :b 2} ``` *note: the default `:threshold` value is 32* At this point the cache has not yet crossed the set threshold of `2`, but if you execute yet another call the story will change: ```clojure (-> C (assoc :a 1) (assoc :b 2) (assoc :c 3)) ;=> {:b 2, :c 3} ``` At this point the operation of the LRU cache looks exactly the same at the FIFO cache. However, the difference becomes apparent when a given cache item is "touched": ```clojure (-> C (assoc :a 1) (assoc :b 2) (.hit :a) ;; ensure :a is used most recently (assoc :c 3)) ;=> {:a 1, :c 3} ``` As you see, hitting the element at the key `:a` will expose the LRU nature of the underlying cache. That is, when the threshold is passed, the cache will expel the **L**east **R**ecently **U**sed element in favor of the new. In this base case the items accessed most recetly were `:c` and `:a`. Like all of the implementations in core.cache, `LRUCache` instances operate like regular maps and are immutable. All caveats apply regarding the [proper usage patterns](./Using.md). LRU cache use case ------------------ The LRU cache eviction policy is very simple to understand and works well in general. However, because the policy requires "age" information, the implementation is somewhat subtle and moderately memory intensive. ### Advantages to using an LRU cache There are a few reasons why you might want to use a LRU cache: * Its logic is easy to understand * It's reasonably fast * It's generally efficient * It works well with data subject to locality concerns * It generally performs better as the cache size increases * Is fairly agile to catch up with changing access patterns ### Disadvantages to using an LRU cache * Tends to perform poorly when elements files are accessed occasionally but consistently while other elements are accessed very frequently for a short duration and never accessed again * It requires more historical data to operate * It requires a larger cache to increase efficiency As always, you should measure your system's characteristics to determine the best eviction strategy for your purposes. core.cache-core.cache-1.0.207/docs/LU.md000066400000000000000000000047451364415562000174550ustar00rootroot00000000000000LU cache ========= The least-used cache (sometimes called "Least Frequently Used") is a [variant of LRU](./LRU.md) that evicts items that are used least frequently once its threshold has been exceeded. > In simple terms, the LU cache will remove the element in the cache that has been accessed the least, regardless of time. *Before reading this page please make sure that you've read and understand the [Basic Usage patterns](./Using.md).* General usage ------------- To create a core.cache `LUCache` instance you should *always* use its associated constructor function `lu-cache-factory` with an optional `:threshold` parameter: ```clojure (ns your.lib (:require [clojure.core.cache :as cache])) (def C (cache/lu-cache-factory {} :threshold 2)) (-> C (assoc :a 1) (assoc :b 2)) ;=> {:a 1, :b 2} ``` *note: the default `:threshold` value is 32* At this point the cache has not yet crossed the item threshold of `2`, but if you execute yet another call the story will change: ```clojure (-> C (assoc :a 1) (assoc :b 2) (assoc :c 3)) ;=> {:b 2, :c 3} ``` At this point the operation of the LU cache looks exactly the same at the FIFO cache. However, the difference becomes apparent when a given cache item is "touched": ```clojure (-> C (assoc :a 1) (assoc :b 2) (.hit :b) (.hit :b) (.hit :a) ;; ensure :a is used most recently (assoc :c 3)) ;=> {:c 3, :b 2} ``` As you see, hitting the key `:b` twice marks it as more important that `:a` even though the latter was "touched" more recently. That is, when the threshold is passed, the cache will expel the **L**east **U**sed element in favor of the element accessed most often. All caveats apply regarding the [proper usage patterns](./Using.md). LU cache use cases ------------------ The LU cache eviction policy is very simple to understand and works well in general. ### Advantages to using an LU cache There are a few reasons why you might want to use an LU cache: * Performs pretty well if access patterns rarely change * Its logic is easy to understand * It's reasonably fast * It works well with data subject to temporal locality concerns ### Disadvantages to using an LU cache * It performs poorly when access patterns change * It requires some historical data to operate * It requires a larger cache to increase efficiency As always, you should measure your system's characteristics to determine the best eviction strategy for your purposes. core.cache-core.cache-1.0.207/docs/Plans.md000066400000000000000000000010111364415562000201710ustar00rootroot00000000000000# Plans for core.cache These were Fogus's plans for core.cache. See https://clojure.atlassian.net/projects/CCACHE/issues/?filter=allopenissues for what is actually being considered. * Most Recently Used cache implementation * Function-backed cache implementation * Random eviction cache implementation * Double-cache lookup implementation * Asynchronous caching protocol * LIRSCache evict * Adaptive eviction caching * test.generative usage * Explore Arc impl. * More documentation and examples core.cache-core.cache-1.0.207/docs/README.md000066400000000000000000000051501364415562000200610ustar00rootroot00000000000000core.cache ========== ## Table of Topics * Overview (this page) * [Including core.cache in your projects](./Including.md) * [Example usages of core.cache](./Using.md) * [Composing caches](./Composing.md) * [Creating custom caches](./Extending.md) * [Building core.cache](./Building.md) * [Plans for core.cache](./Plans.md) ## The problem Value caching is sometimes needed. This need is often driven by the desire is to avoid calculating expensive operations such as inherently costly algorithms or I/O more often than necessary. The naive solution for this need is to perform some expensive operation once and cache the result. Therefore, whenever the same calculation is needed in the future it can be retrieved from cache more quickly than simply recalculating from scratch. While effective for small domains, the naive caching of many expensive calculations or cyclopean results can consume available memory quickly. Therefore, the ideal situation is to expunge stored results that have expired, meant for single-use or less likely to be needed again. There are many general-purpose and domain-specific strategies for efficient cache population and eviction. The core.cache library provides implementations of common caching strategies as well as a mechanism for implementing custom strategies. ## Overview core.cache is a Clojure contrib library providing the following features: * An underlying `CacheProtocol` used as the base abstraction for implementing new synchronous caches * A `defcache` macro for hooking your `CacheProtocol` implementations into the Clojure associative data capabilities. * Implementations of some common caching strategies, including: - [First-in-first-out](./FIFO.md) - [Least-recently-used](./LRU.md) - [Least-used](./LU.md) - [Time-to-live](./TTL.md) - Function-backed cache (work in progress) - Soft-reference cache (work in progress) * Implementation of an efficient buffer replacement policy based on the *low inter-reference recency set* algorithm ([LIRSCache](./LIRS.md)) described in the [LIRS](http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.116.2184) paper * Factory functions for each existing cache type *The implementation of core.cache is based on and heavily influenced by the excellent ['Memoize done right'](http://kotka.de/blog/2010/03/memoize_done_right.html) by Meikel Brandmeyer* ## 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) * [Examples and documentation](http://github.com/clojure/core.cache/wiki)core.cache-core.cache-1.0.207/docs/TTL.md000066400000000000000000000036771364415562000176030ustar00rootroot00000000000000TTL cache ========== The time-to-live cache is one that evicts items that are older than a time-to-live threshold (in milliseconds). *Before reading this page please make sure that you've read and understand the [Basic Usage patterns](./Using.md).* General usage ------------- To create a core.cache `TTLCacheQ` instance you should *always* use its associated constructor function `ttl-cache-factory` with an optional `:ttl` parameter: ```clojure (ns your.lib (:require [clojure.core.cache :as cache])) (def C (cache/ttl-cache-factory {} :ttl 1000)) (-> C (assoc :a 1) (assoc :b 2)) ;=> {:a 1, :b 2} ``` *note: the default `:ttl` value is 2 seconds* At this point the cache is fresh and younger than one second (that is, depending on how fast you read), but if you execute yet another call the story will change: ```clojure (def sleepy #(do (Thread/sleep %2) %)) (-> C (assoc :a 1) (assoc :b 2) (sleepy 1500) (assoc :c 3)) ;=> {:c 3} ``` At this point the operation of the TTL cache is exposed. As you see, sleeping in between adding the keys `:a` and `:b` causes them to be evicted on the next insertion. All caveats apply regarding the [proper usage patterns](./Using.md). TTL cache use cases -------------------- The TTL cache eviction policy is very simple to understand and works well for certain scenarios. However, because the policy requires "age" information, the implementation is somewhat subtle and moderately memory intensive. ### Advantages to using an TTL cache There are a few reasons why you might want to use a TTL cache: * Its logic is easy to understand * It's reasonably fast * It works well with data subject to temporal concerns ### Disadvantages to using an TTL cache * It requires more historical data to operate * Cache size does not generally help its efficiency As always, you should measure your system's characteristics to determine the best eviction strategy for your purposes. core.cache-core.cache-1.0.207/docs/Using.md000066400000000000000000000063241364415562000202150ustar00rootroot00000000000000# Using core.cache *note: see the page on [including core.cache](./Including.md) before you begin this section* ## Basic usage pattern To use the cache implementations or extend the core.cache protocols you first need to require the proper namespace: ```clojure (require '[clojure.core.cache :as cache]) ``` Next you should create an instance of a specific cache type, optionally seeded: ```clojure (def C (cache/fifo-cache-factory {:a 1, :b 2})) ``` To find a value in a map by its key you have a couple choices: ```clojure (cache/lookup C :a) ;=> 1 (:b C) ;=> 2 ``` To ensure the proper cache policies are followed for each specific type, the following `has?/hit/miss` pattern should be used: ```clojure (if (cache/has? C :c) ;; has? checks that the cache contains an item (cache/hit C :c) ;; hit returns a cache with any relevant internal information updated (cache/miss C :c 42)) ;; miss returns a new cache with the new item and without evicted entries ;=> {:a 1, :b 2, :c 42} ``` Using the `has?/hit/miss` pattern ensures that the thresholding and eviction logic for each implementation works properly. It is built into the `through` and `through-cache` functions, as well as `clojure.core.cache.wrapped/lookup-or-miss`. **Avoid this pattern at your own risk.** Finally, to explicitly evict an element in a cache, use the `evict` function: ```clojure (cache/evict C :b) ;=> {:a 1} ``` For specific information about eviction policies and thresholds, view the specific documentation for each cache type listed in the next section. Sometimes you may wish to cache a function except when it returns certain values, such as a resource-loading function that may return `nil` if the resource is (temporarily) unavailable. Because of the edge cases that can arise with doing multiple lookups on a cache -- protections from which are baked into `through`, `through-cache`, and `lookup-or-miss` -- it is better to write your code to simply cache all results and then, post-retrieval, `evict` the key if the result is something you don't want cached: ```clojure (let [result (wrapped/lookup-or-miss C :c load-my-resource)] (when (nil? result) ; or seq or whatever condition should exclude this result (wrapped/evict C :c)) result) ``` ## Builtin cache implementations core.cache comes with a number of builtin immutable cache implementations, including (*click through for specific information*): * [FIFO cache](./FIFO.md) * [LRU cache](./LRU.md) * [LU cache](./LU.md) * [TTL cache](./TTL.md) * [LIRS cache](./LIRS.md) * Function-backed cache (work in progress) * Soft-reference cache (work in progress) The core.cache implementations are backed by any map-like object. Additionally, each cache implements the Clojure map behaviors and can therefore serve as special maps or even as backing stores for other cache implementations. For caches taking a limit argument, the eviction policies tend not to apply until the limit has been exceeded. ## Extending core.cache See the section [on creating custom caches](./Extending.md) for more information. ## Nesting cache types See the section [on composing caches](./Composing.md) for more information. core.cache-core.cache-1.0.207/docs/release-notes/000077500000000000000000000000001364415562000213475ustar00rootroot00000000000000core.cache-core.cache-1.0.207/docs/release-notes/release-0.5.0.markdown000066400000000000000000000053651364415562000252020ustar00rootroot00000000000000core.cache v0.5.0 Release Notes =============================== core.cache is a new Clojure contrib library providing the following features: * An underlying `CacheProtocol` used as the base abstraction for implementing new synchronous caches * A `defcache` macro for hooking your `CacheProtocol` implementations into the Clojure associative data capabilities. * Immutable implementations of some basic caching strategies - First-in-first-out (FIFOCache) - Least-recently-used (LRUCache) - Least-used (LUCache) - Time-to-live (TTLCache) - Naive cache (BasicCache) * Implementation of an efficient buffer replacement policy based on the *low inter-reference recency set* algorithm (LIRSCache) described in the [LIRS](http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.116.2184) paper * Factory functions for each existing cache type core.cache is based on a library named Clache, found at http://github.com/fogus/clache that is planned for deprecation. Absorb ------ You can use core.cache in your [Leiningen](https://github.com/technomancy/leiningen) and [Cake](https://github.com/flatland/cake) projects with the following `:dependencies` directive in your `project.clj` file: [org.clojure/core.cache "0.5.0"] For Maven-driven projects, use the following slice of XML in your `pom.xml`'s `` section: org.clojure core.cache 0.5.0 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) * Examples and documentation -- in progress Changes from Clache ------------------- The v0.5.0 version of core.cache is based almost wholly on the final version of Clache, with the following changes: * An addition of an `evict` function on the `CacheProtocol` used to explicitly remove a value from a cache based on a key. All of the existing cache types implement this function *except* for `LIRSCache`. * The addition of cache factory functions for all of the existing cache types * The associative structure behaviors are defined solely in terms of the underlying `CacheProtocol` * The `SoftCache` implementation was buggy and removed for now Plans ----- The following capabilities are under design, development, or consideration for future versions of core.cache: * Asynchronous caching protocol * `LIRSCache evict` * Removal of the `seed` function from the `CacheProtocol` * Reimplementation of a cache based on soft references * test.generative usage * Deprecation of Clache * Documentation and examples More planning is needed around capabilities not listed nor thought of. core.cache-core.cache-1.0.207/docs/release-notes/release-0.6.1.markdown000066400000000000000000000051111364415562000251710ustar00rootroot00000000000000core.cache v0.6.1 Release Notes =============================== core.cache is a new Clojure contrib library providing the following features: * An underlying `CacheProtocol` used as the base abstraction for implementing new synchronous caches * A `defcache` macro for hooking your `CacheProtocol` implementations into the Clojure associative data capabilities. * Immutable implementations of some basic caching strategies - First-in-first-out (FIFOCache) - Least-recently-used (LRUCache) - Least-used (LUCache) - Time-to-live (TTLCache) - Soft-Reference cache (SoftCache) - Naive cache (BasicCache) * Implementation of an efficient buffer replacement policy based on the *low inter-reference recency set* algorithm (LIRSCache) described in the [LIRS](http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.116.2184) paper * Factory functions for each existing cache type Absorb ------ You can use core.cache in your [Leiningen](https://github.com/technomancy/leiningen) and [Cake](https://github.com/flatland/cake) projects with the following `:dependencies` directive in your `project.clj` file: [org.clojure/core.cache "0.6.1"] For Maven-driven projects, use the following slice of XML in your `pom.xml`'s `` section: org.clojure core.cache 0.6.1 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.5.0 ------------------- The v0.6.1 version of core.cache contains the following changes: * The addition of a cache built on Java soft references * Bug fix for LRU and LU caches disabling the eviction of duplicate keys prior to threshold. * The factory function optional argument named `:limit` was changed to `:threshold`. * The default thresholds set by the factory functions were adjusted. Plans ----- The following capabilities are under design, development, or consideration for future versions of core.cache: * 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/docs/release-notes/release-0.6.2.markdown000066400000000000000000000047731364415562000252070ustar00rootroot00000000000000core.cache v0.6.2 Release Notes =============================== core.cache is a Clojure contrib library providing the following features: * An underlying `CacheProtocol` used as the base abstraction for implementing new synchronous caches * A `defcache` macro for hooking your `CacheProtocol` implementations into the Clojure associative data capabilities. * Immutable implementations of some basic caching strategies - First-in-first-out (FIFOCache) - Least-recently-used (LRUCache) - Least-used (LUCache) - Time-to-live (TTLCache) - Soft-Reference cache (SoftCache) - Naive cache (BasicCache) * Implementation of an efficient buffer replacement policy based on the *low inter-reference recency set* algorithm (LIRSCache) described in the [LIRS](http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.116.2184) paper * Factory functions for each existing cache type Absorb ------ You can use core.cache in your [Leiningen](https://github.com/technomancy/leiningen) and [Cake](https://github.com/flatland/cake) projects with the following `:dependencies` directive in your `project.clj` file: [org.clojure/core.cache "0.6.2"] For Maven-driven projects, use the following slice of XML in your `pom.xml`'s `` 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.html000066400000000000000000000305601364415562000177270ustar00rootroot00000000000000 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.xml000066400000000000000000000027071364415562000171740ustar00rootroot00000000000000 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.sh000077500000000000000000000001521364415562000201520ustar00rootroot00000000000000#!/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/000077500000000000000000000000001364415562000164405ustar00rootroot00000000000000core.cache-core.cache-1.0.207/src/main/000077500000000000000000000000001364415562000173645ustar00rootroot00000000000000core.cache-core.cache-1.0.207/src/main/clojure/000077500000000000000000000000001364415562000210275ustar00rootroot00000000000000core.cache-core.cache-1.0.207/src/main/clojure/clojure/000077500000000000000000000000001364415562000224725ustar00rootroot00000000000000core.cache-core.cache-1.0.207/src/main/clojure/clojure/core/000077500000000000000000000000001364415562000234225ustar00rootroot00000000000000core.cache-core.cache-1.0.207/src/main/clojure/clojure/core/cache.clj000066400000000000000000000543161364415562000251700ustar00rootroot00000000000000; 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/000077500000000000000000000000001364415562000244655ustar00rootroot00000000000000core.cache-core.cache-1.0.207/src/main/clojure/clojure/core/cache/wrapped.clj000066400000000000000000000175631364415562000266350ustar00rootroot00000000000000; 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/000077500000000000000000000000001364415562000174175ustar00rootroot00000000000000core.cache-core.cache-1.0.207/src/test/clojure/000077500000000000000000000000001364415562000210625ustar00rootroot00000000000000core.cache-core.cache-1.0.207/src/test/clojure/clojure/000077500000000000000000000000001364415562000225255ustar00rootroot00000000000000core.cache-core.cache-1.0.207/src/test/clojure/clojure/core/000077500000000000000000000000001364415562000234555ustar00rootroot00000000000000core.cache-core.cache-1.0.207/src/test/clojure/clojure/core/cache/000077500000000000000000000000001364415562000245205ustar00rootroot00000000000000core.cache-core.cache-1.0.207/src/test/clojure/clojure/core/cache/wrapped_test.clj000066400000000000000000000033601364415562000277150ustar00rootroot00000000000000; 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.clj000066400000000000000000000526361364415562000262650ustar00rootroot00000000000000; 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)))))))