Cache

interface Cache<K, V>

Mutable, fixed-capacity cache whose eviction strategy depends on the specific implementation.

A Cache is useful whenever some expensive computation (e.g. an MGU computation, a number-format conversion, a parsed representation) is repeatedly requested for the same input, and memory usage must be bounded: unlike a plain MutableMap, a Cache never grows past capacity, evicting older entries (following the policy of the concrete implementation) as new ones are stored. Instances are created via the factory methods in the companion object, e.g. Cache.lru or Cache.simpleLru.

For instance, it.unibo.tuprolog.unify.CachedUnificator (in the :unify module) uses a Cache to memoize the results of most general unifier computations:

private val mguCache: Cache<MguRequest, Substitution> = Cache.simpleLru(cacheCapacity)

Type Parameters

K

is the type of the keys used for indexing items in this cache

V

is the type of the values stored in this cache

Types

Link copied to clipboard
object Companion

Properties

Link copied to clipboard
abstract val capacity: Int

Retrieves the maximum amount of items this cache may ever store

Link copied to clipboard
abstract val size: Int

Retrieves the amount of items currently cached by this cache

Functions

Link copied to clipboard
abstract operator fun get(key: K): Optional<out V>

Retrieves the cached value corresponding to the provided key

Link copied to clipboard
open fun getOrSet(key: K, valueGenerator: () -> V): V

Retrieves the cached value corresponding to the provided key, or stores a cache for the key in case it is missing

Link copied to clipboard
abstract operator fun set(key: K, value: V): Optional<out Pair<K, V>>

Stores a new key-value pair in this cache, possibly evicting some previously stored key-value pair

Link copied to clipboard
abstract fun toMap(): Map<K, V>

Converts this cache to an immutable map, containing a snapshot of all the key-value pairs currently cached

Link copied to clipboard
abstract fun toSequence(): Sequence<Pair<K, V>>

Converts this cache to a sequence of key-value pairs, containing a snapshot of all the key-value pairs currently cached