Class CachedValue<K,V>

java.lang.Object
com.amalgamasimulation.utils.CachedValue<K,V>
Type Parameters:
K - type of the key, typically Double (for simulation time) or Long (for simulated events count)
V - type of the calculated value

public class CachedValue<K,V> extends Object
Class for caching the results of some calculations with respect to some key. If the key changes, the value should be recalculated whereas if the key stays the same, the previously calculated value is returned.

The typical use case of this class is caching some simulation model statistics and only recalculating them if simulation engine has executed some events since the last calculation.

This class is null-safe, both null keys and null values are allowed and are treated as regular values.

Author:
Andrey Malykhanov
  • Constructor Details

    • CachedValue

      public CachedValue(Supplier<K> keySupplier, Supplier<V> valueSupplier)
      Creates a new cached value with the specified suppliers of key and value
      Parameters:
      keySupplier - supplier of the key
      valueSupplier - supplier of the value
  • Method Details

    • get

      public V get()
      Returns the value. First, uses a key supplier to get the current key.

      If the current key is equal to the key used for the previous value calculation, the cached value is returned.

      Otherwise, if the key is new, calculates the value using the supplier, puts it into the cache and returns the newly calculated value

      Returns:
      value, cached or newly calculated based on the key