Interface Cache<K,​V>

  • Type Parameters:
    K - key type of cache (must be immutable and have correct hashCode & equals)
    V - value type of cache (should, for monitoring and predictable memory effect of eviction, typically, be of "similar" size for all keys; else consider simply using separate Cache, if feasible)
    All Superinterfaces:
    AutoCloseable, BaseCache<K,​V>
    All Known Implementing Classes:
    DelegatingNullSafeCache

    public interface Cache<K,​V>
    extends BaseCache<K,​V>
    Cache of keys to values.

    Users typically obtain implementations from the CacheProvider.

    Caches are not Maps! Differences include that a Map persists all elements that are added to it until they are explicitly removed. A Cache on the other hand is generally configured to evict entries automatically, in order to constrain its memory footprint, based on some policy (quoted from Caffeine's or Guava's introduction). Another notable difference, enforced by this caching API, is that caches should not be thought of as data structures that you put something in somewhere in your code to get it out of somewhere else. Instead, a Cache is "just a façade" to a CacheFunction's get. This design enforces proper encapsulation, and helps you not to screw up the content of your cache (like you easily can, and usually do, when you use a Map as a cache).

    The implementation of this API is, typically, backed by established cache frameworks, such as Ehcache, Infinispan, Guava's, Caffeine, ..., imcache, cache2k, ... etc.

    Implementations of this interface are expected to be safe to use from multiple threads concurrently.

    Author:
    Michael Vorburger.ch
    • Method Detail

      • get

        @NonNull V get​(@NonNull K key)
        Get cache entry. If the cache does not currently contain an entry under this key, then one is created, using the CacheFunction given when the cache was created.
        Parameters:
        key - key of cache entry
        Returns:
        value, never null (but may be an Optional)
        Throws:
        BadCacheFunctionRuntimeException - if the cache's function returned null value
        NullPointerException - if the cache's users passed a null key
      • get

        com.google.common.collect.ImmutableMap<K,​V> get​(Iterable<? extends K> keys)
        Get several cache entries, in one go.
        Parameters:
        keys - list of keys of cache entries
        Returns:
        Map of cache keys and values (neither ever null, but may be an Optional)
        Throws:
        BadCacheFunctionRuntimeException - if the cache's function returned null value
        NullPointerException - if the cache's users passed a null key
      • get

        default com.google.common.collect.ImmutableMap<K,​V> get​(@NonNull K... keys)
        Convenience short-cut to get(Iterable) with vararg syntax.