Class CaffeineCache

java.lang.Object
org.springframework.cache.support.AbstractValueAdaptingCache
org.springframework.cache.caffeine.CaffeineCache
All Implemented Interfaces:
Cache

public class CaffeineCache extends AbstractValueAdaptingCache
Spring Cache adapter implementation on top of a Caffeine Cache instance.

Supports the retrieve(Object) and retrieve(Object, Supplier) operations through Caffeine's AsyncCache, when provided via the CaffeineCache(String, AsyncCache, boolean) constructor.

Requires Caffeine 3.0 or higher, as of Spring Framework 6.1.

Since:
4.3
Author:
Ben Manes, Juergen Hoeller, Stephane Nicoll
See Also:
  • Constructor Details

    • CaffeineCache

      public CaffeineCache(String name, com.github.benmanes.caffeine.cache.Cache<Object,Object> cache)
      Create a CaffeineCache instance with the specified name and the given internal Cache to use.
      Parameters:
      name - the name of the cache
      cache - the backing Caffeine Cache instance
    • CaffeineCache

      public CaffeineCache(String name, com.github.benmanes.caffeine.cache.Cache<Object,Object> cache, boolean allowNullValues)
      Create a CaffeineCache instance with the specified name and the given internal Cache to use.
      Parameters:
      name - the name of the cache
      cache - the backing Caffeine Cache instance
      allowNullValues - whether to accept and convert null values for this cache
    • CaffeineCache

      public CaffeineCache(String name, com.github.benmanes.caffeine.cache.AsyncCache<Object,Object> cache, boolean allowNullValues)
      Create a CaffeineCache instance with the specified name and the given internal AsyncCache to use.
      Parameters:
      name - the name of the cache
      cache - the backing Caffeine AsyncCache instance
      allowNullValues - whether to accept and convert null values for this cache
      Since:
      6.1
  • Method Details

    • getName

      public final String getName()
      Description copied from interface: Cache
      Return the cache name.
    • getNativeCache

      public final com.github.benmanes.caffeine.cache.Cache<Object,Object> getNativeCache()
      Return the internal Caffeine Cache (possibly an adapter on top of an getAsyncCache()).
    • getAsyncCache

      public final com.github.benmanes.caffeine.cache.AsyncCache<Object,Object> getAsyncCache()
      Return the internal Caffeine AsyncCache.
      Throws:
      IllegalStateException - if no AsyncCache is available
      Since:
      6.1
      See Also:
    • get

      @Nullable public <T> T get(Object key, Callable<T> valueLoader)
      Description copied from interface: Cache
      Return the value to which this cache maps the specified key, obtaining that value from valueLoader if necessary. This method provides a simple substitute for the conventional "if cached, return; otherwise create, cache and return" pattern.

      If possible, implementations should ensure that the loading operation is synchronized so that the specified valueLoader is only called once in case of concurrent access on the same key.

      If the valueLoader throws an exception, it is wrapped in a Cache.ValueRetrievalException

      Parameters:
      key - the key whose associated value is to be returned
      Returns:
      the value to which this cache maps the specified key
      See Also:
    • retrieve

      @Nullable public CompletableFuture<?> retrieve(Object key)
      Description copied from interface: Cache
      Return the value to which this cache maps the specified key, wrapped in a CompletableFuture. This operation must not block but is allowed to return a completed CompletableFuture if the corresponding value is immediately available.

      Can return null if the cache can immediately determine that it contains no mapping for this key (e.g. through an in-memory key map). Otherwise, the cached value will be returned in the CompletableFuture, with null indicating a late-determined cache miss. A nested Cache.ValueWrapper potentially indicates a nullable cached value; the cached value may also be represented as a plain element if null values are not supported. Calling code needs to be prepared to handle all those variants of the result returned by this method.

      Parameters:
      key - the key whose associated value is to be returned
      Returns:
      the value to which this cache maps the specified key, contained within a CompletableFuture which may also be empty when a cache miss has been late-determined. A straight null being returned means that the cache immediately determined that it contains no mapping for this key. A Cache.ValueWrapper contained within the CompletableFuture indicates a cached value that is potentially null; this is sensible in a late-determined scenario where a regular CompletableFuture-contained null indicates a cache miss. However, a cache may also return a plain value if it does not support the actual caching of null values, avoiding the extra level of value wrapping. Spring's cache processing can deal with all such implementation strategies.
      See Also:
    • retrieve

      public <T> CompletableFuture<T> retrieve(Object key, Supplier<CompletableFuture<T>> valueLoader)
      Description copied from interface: Cache
      Return the value to which this cache maps the specified key, obtaining that value from valueLoader if necessary. This method provides a simple substitute for the conventional "if cached, return; otherwise create, cache and return" pattern, based on CompletableFuture. This operation must not block.

      If possible, implementations should ensure that the loading operation is synchronized so that the specified valueLoader is only called once in case of concurrent access on the same key.

      Null values always indicate a user-level null value with this method. The provided CompletableFuture handle produces a value or raises an exception. If the valueLoader raises an exception, it will be propagated to the returned CompletableFuture handle.

      Parameters:
      key - the key whose associated value is to be returned
      Returns:
      the value to which this cache maps the specified key, contained within a CompletableFuture which will never be null. The provided future is expected to produce a value or raise an exception.
      See Also:
    • lookup

      @Nullable protected Object lookup(Object key)
      Description copied from class: AbstractValueAdaptingCache
      Perform an actual lookup in the underlying store.
      Specified by:
      lookup in class AbstractValueAdaptingCache
      Parameters:
      key - the key whose associated value is to be returned
      Returns:
      the raw store value for the key, or null if none
    • put

      public void put(Object key, @Nullable Object value)
      Description copied from interface: Cache
      Associate the specified value with the specified key in this cache.

      If the cache previously contained a mapping for this key, the old value is replaced by the specified value.

      Actual registration may be performed in an asynchronous or deferred fashion, with subsequent lookups possibly not seeing the entry yet. This may for example be the case with transactional cache decorators. Use Cache.putIfAbsent(java.lang.Object, java.lang.Object) for guaranteed immediate registration.

      If the cache is supposed to be compatible with CompletableFuture and reactive interactions, the put operation needs to be effectively non-blocking, with any backend write-through happening asynchronously. This goes along with a cache implemented and configured to support Cache.retrieve(Object) and Cache.retrieve(Object, Supplier).

      Parameters:
      key - the key with which the specified value is to be associated
      value - the value to be associated with the specified key
      See Also:
    • putIfAbsent

      @Nullable public Cache.ValueWrapper putIfAbsent(Object key, @Nullable Object value)
      Description copied from interface: Cache
      Atomically associate the specified value with the specified key in this cache if it is not set already.

      This is equivalent to:

      
       ValueWrapper existingValue = cache.get(key);
       if (existingValue == null) {
           cache.put(key, value);
       }
       return existingValue;
       
      except that the action is performed atomically. While all out-of-the-box CacheManager implementations are able to perform the put atomically, the operation may also be implemented in two steps, e.g. with a check for presence and a subsequent put, in a non-atomic way. Check the documentation of the native cache implementation that you are using for more details.

      The default implementation delegates to Cache.get(Object) and Cache.put(Object, Object) along the lines of the code snippet above.

      Parameters:
      key - the key with which the specified value is to be associated
      value - the value to be associated with the specified key
      Returns:
      the value to which this cache maps the specified key (which may be null itself), or also null if the cache did not contain any mapping for that key prior to this call. Returning null is therefore an indicator that the given value has been associated with the key.
      See Also:
    • evict

      public void evict(Object key)
      Description copied from interface: Cache
      Evict the mapping for this key from this cache if it is present.

      Actual eviction may be performed in an asynchronous or deferred fashion, with subsequent lookups possibly still seeing the entry. This may for example be the case with transactional cache decorators. Use Cache.evictIfPresent(java.lang.Object) for guaranteed immediate removal.

      If the cache is supposed to be compatible with CompletableFuture and reactive interactions, the evict operation needs to be effectively non-blocking, with any backend write-through happening asynchronously. This goes along with a cache implemented and configured to support Cache.retrieve(Object) and Cache.retrieve(Object, Supplier).

      Parameters:
      key - the key whose mapping is to be removed from the cache
      See Also:
    • evictIfPresent

      public boolean evictIfPresent(Object key)
      Description copied from interface: Cache
      Evict the mapping for this key from this cache if it is present, expecting the key to be immediately invisible for subsequent lookups.

      The default implementation delegates to Cache.evict(Object), returning false for not-determined prior presence of the key. Cache providers and in particular cache decorators are encouraged to perform immediate eviction if possible (e.g. in case of generally deferred cache operations within a transaction) and to reliably determine prior presence of the given key.

      Parameters:
      key - the key whose mapping is to be removed from the cache
      Returns:
      true if the cache was known to have a mapping for this key before, false if it did not (or if prior presence could not be determined)
      See Also:
    • clear

      public void clear()
      Description copied from interface: Cache
      Clear the cache through removing all mappings.

      Actual clearing may be performed in an asynchronous or deferred fashion, with subsequent lookups possibly still seeing the entries. This may for example be the case with transactional cache decorators. Use Cache.invalidate() for guaranteed immediate removal of entries.

      If the cache is supposed to be compatible with CompletableFuture and reactive interactions, the clear operation needs to be effectively non-blocking, with any backend write-through happening asynchronously. This goes along with a cache implemented and configured to support Cache.retrieve(Object) and Cache.retrieve(Object, Supplier).

      See Also:
    • invalidate

      public boolean invalidate()
      Description copied from interface: Cache
      Invalidate the cache through removing all mappings, expecting all entries to be immediately invisible for subsequent lookups.
      Returns:
      true if the cache was known to have mappings before, false if it did not (or if prior presence of entries could not be determined)
      See Also: