Interface Cache<K,V>

Type Parameters:
K - key type — must have a stable hashCode/equals
V - value type

public interface Cache<K,V>
A named cache. Obtained from a CacheManager, safe to hold in a handler field and share across threads.

 User user = users.get(id, repo::findById);
 

get(K, java.util.function.Function<? super K, ? extends V>) is the only method most code needs. The rest exist for the cases it cannot express: reading without populating, writing a value computed elsewhere, and invalidating.

  • Method Summary

    Modifier and Type
    Method
    Description
    long
    Approximate entry count.
    get(K key, Function<? super K,? extends V> loader)
    Returns the cached value, computing and storing it with loader if absent.
    The cached value, or null if absent.
    void
    Drops key.
    void
    Drops every entry.
    void
    put(K key, V value)
    Stores value, replacing any existing entry.
    Hit/miss counters since this cache was built, or CacheStats.DISABLED when the backend was not asked to record them.
  • Method Details

    • get

      V get(K key, Function<? super K,? extends V> loader)
      Returns the cached value, computing and storing it with loader if absent.

      The loader runs at most once per key across concurrent callers; the others wait for it rather than each computing their own. A loader returning null stores nothing and null is returned.

    • getIfPresent

      V getIfPresent(K key)
      The cached value, or null if absent. Never invokes a loader.
    • put

      void put(K key, V value)
      Stores value, replacing any existing entry.
    • invalidate

      void invalidate(K key)
      Drops key. Does nothing if it was absent.
    • invalidateAll

      void invalidateAll()
      Drops every entry.
    • estimatedSize

      long estimatedSize()
      Approximate entry count. Approximate because eviction is asynchronous in most backends.
    • stats

      CacheStats stats()
      Hit/miss counters since this cache was built, or CacheStats.DISABLED when the backend was not asked to record them.