Class CachedSupplier<T>


  • public class CachedSupplier<T>
    extends java.lang.Object
    Supplier that will cache a computed value and always supply the same value. It can be used to lazily compute data. For example:
    
     CachedSupplier<Integer> value = new CachedSupplier<>(() -> {
         Integer result;
         // Do some expensive computation.
         return result;
     });
    
     if (a) {
         // We need the result of the expensive computation.
         Integer r = value.get();
     }
    
     if (b) {
         // We also need the result of the expensive computation.
         Integer r = value.get();
     }
    
     // If neither a nor b are true, we avoid doing the computation at all.
     
    • Constructor Summary

      Constructors 
      Constructor Description
      CachedSupplier​(com.google.common.base.Supplier<T> supplier)
      Creates a new supplier.
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      T get()
      Obtains the value.
      boolean isValid()
      Checks if the contents of the cache are valid.
      void precomputed​(T t)
      In some cases, we may be able to precompute the cache value (or load it from somewhere we had previously stored it).
      void reset()
      Resets the cache forcing a get() on the supplier next time get() is invoked.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • CachedSupplier

        public CachedSupplier​(com.google.common.base.Supplier<T> supplier)
        Creates a new supplier.
    • Method Detail

      • get

        public T get()
        Obtains the value.
        Returns:
        the value, either cached (if one exists) or computed
      • reset

        public void reset()
        Resets the cache forcing a get() on the supplier next time get() is invoked.
      • precomputed

        public void precomputed​(T t)
        In some cases, we may be able to precompute the cache value (or load it from somewhere we had previously stored it). This method allows the cache value to be loaded.

        If this method is invoked, then an invocation of get() will not trigger an invocation of the supplier provided in the constructor.

        Parameters:
        t - the new cache contents; will replace any currently cache content, if one exists
      • isValid

        public boolean isValid()
        Checks if the contents of the cache are valid.
        Returns:
        are there valid contents in the cache?