Package de.arstwo.twotil
Class Cached<K,V>
java.lang.Object
de.arstwo.twotil.Cached<K,V>
- Type Parameters:
K- anyV- any
- All Implemented Interfaces:
Function<K,V>
Simple key->value caching functionality, for both as a class and functional usage.
Null and thread safe, results are cached indefinitely as long as the function is in scope.
Usage example:
Cached<Long, Person> cache = new Cached(myDB::getByID);
// ...
Person person = cache.get(personID);
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionNecessary for functional usage.static <I,O> Function <I, O> Convenience accessor for functional feeling.voidclear()Clears the cache.Gets a value from the cache or the source.voidCleanup method to remove individual items.voidReplaces a cache entry.booleanReplaces a cache entry if it matches the old value.
-
Constructor Details
-
Cached
Creates a new cache with source as the supplier.- Parameters:
source- accessor to the data to cache.
-
-
Method Details
-
cached
Convenience accessor for functional feeling.- Type Parameters:
I- anyO- any- Parameters:
source- supplier for cache misses.- Returns:
- A function that caches the result of the given source function.
-
get
Gets a value from the cache or the source.- Parameters:
key- the key to look for.- Returns:
- the value retrieved either from cache, or from the source.
-
apply
Necessary for functional usage. -
clear
public void clear()Clears the cache. -
removeIf
Cleanup method to remove individual items.Values can be null.
- Parameters:
filter- a predicate that returns true if an entry should be removed.
-
replace
Replaces a cache entry.- Parameters:
key- entry keynewValue- new value to set
-
replaceIf
Replaces a cache entry if it matches the old value.- Parameters:
key- entry keyoldValue- expected old valuenewValue- new value to set- Returns:
- true if the entry was replaced, false otherwise, which usually indicates that the values did not match.
-