A simple caching library for keeping a certain fixed amount of your computed objects with an LRU eviction strategy.
Complexity (usually) | Description |
---|---|
O(mapper function) |
Fetching unseen element |
O(1) |
Fetching seen element |
O(1) |
Eviction of LRU element |
- The result is computed and the value is stored in the
Hashmap
in anew Node
- The element is added as
last
- The result is stored in the
Hashmap
, so it can be fetched and extracted from theNode
- The element is removed from its current position and
prev
andnext
get linked together - The element is added as
last
first
points to the LRU elementfirst.object
is removed from theHashmap
first.next
is the newfirst
first.prev
gets unlinked
Go for it - I tried to make everything as readable and modifiable as possible. Check out the explanation below, and the license in the 'LICENSE' file. Regardless of the license, it would be cool if you somehow mentioned, that you got this code from here :)
- Add as library (here shown in IntelliJ) or add the code directly to your project
- Create a new Cache instance with
DanielsCache<O, R> cache = new DanielsCache<>(int maxSize, Function<O, R> mapper);
O
is the input type e.g. aString
from an incoming REST requestR
is the computed type e.g. the object created from the REST string
- Use
cache.get(O object)
to get the correspondingR result
- The result is computed if it is not in the cache
- But simply fetched if it is
- Eventually the cache fills up, and the LRU (least recently used) element is evicted