Class Cached<K,V>

java.lang.Object
de.arstwo.twotil.Cached<K,V>
Type Parameters:
K - any
V - any
All Implemented Interfaces:
Function<K,V>

public class Cached<K,V> extends Object implements 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 Details

    • Cached

      public Cached(Function<K,V> source)
      Creates a new cache with source as the supplier.
      Parameters:
      source - accessor to the data to cache.
  • Method Details

    • cached

      public static <I, O> Function<I,O> cached(Function<I,O> source)
      Convenience accessor for functional feeling.
      Type Parameters:
      I - any
      O - any
      Parameters:
      source - supplier for cache misses.
      Returns:
      A function that caches the result of the given source function.
    • get

      public V get(K key)
      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

      public V apply(K key)
      Necessary for functional usage.
      Specified by:
      apply in interface Function<K,V>
      Parameters:
      key - the key to look for.
      Returns:
      the value retrieved either from cache, or from the source.
    • clear

      public void clear()
      Clears the cache.
    • removeIf

      public void removeIf(Predicate<? super Map.Entry<K,V>> filter)
      Cleanup method to remove individual items.

      Values can be null.

      Parameters:
      filter - a predicate that returns true if an entry should be removed.
    • replace

      public void replace(K key, V newValue)
      Replaces a cache entry.
      Parameters:
      key - entry key
      newValue - new value to set
    • replaceIf

      public boolean replaceIf(K key, V oldValue, V newValue)
      Replaces a cache entry if it matches the old value.
      Parameters:
      key - entry key
      oldValue - expected old value
      newValue - new value to set
      Returns:
      true if the entry was replaced, false otherwise, which usually indicates that the values did not match.