Class CachedValue<T>

java.lang.Object
org.ametys.core.util.CachedValue<T>
Type Parameters:
T - The type of the cached value

public class CachedValue<T> extends Object
A cached value. It can be constructed with withInitial(java.util.function.Supplier<T>) with a Supplier to pass in order to compute the value to cache on the first call of get().
It can also be constructed with withExpiryDuration(java.util.function.Supplier<T>, java.time.Duration) with the Supplier and an expiry Duration to automatically force the reload of the value.
The supplier is ensured to be called once (until uncache() is called, or after the expiry duration has elapsed since the last computing), even with multiple callers at the same time.
The returned value by the supplier must not be null
  • Method Details

    • withInitial

      public static <T> CachedValue<T> withInitial(Supplier<T> supplier)
      Creates a cached value. The value will be computed by invoking the given supplier when the get() method will be called the first time.
      Type Parameters:
      T - The type of the cached value
      Parameters:
      supplier - The supplier which will be invoked only once in order to compute the value to cache. The value must not be null
      Returns:
      The CachedValue
    • withExpiryDuration

      public static <T> CachedValue<T> withExpiryDuration(Supplier<T> supplier, Duration expiryDuration)
      Creates a cached value. The value will be computed by invoking the given supplier when the get() method will be called the very first time, and every first time after the given Duration is expired.
      Type Parameters:
      T - The type of the cached value
      Parameters:
      supplier - The supplier which will be invoked only once in order to compute the value to cache. The value must not be null
      expiryDuration - The expiry duration
      Returns:
      The CachedValue
    • get

      public T get()
      Returns the value. If it is the first time it is called, then it is computed by invoking the supplier function. Otherwise, the cached value is returned.
      Returns:
      the value
    • uncache

      public void uncache()
      Uncache the value. Mostly to force to re-compute the value.