TtlCache

class TtlCache<K, V>(val ttl: Duration, val maxSize: Int = Int.MAX_VALUE, timeSource: TimeSource.WithComparableMarks = TimeSource.Monotonic)

A cache whose entries expire once ttl has elapsed since they were stored.

An entry is live while its age is strictly less than ttl; at exactly ttl it is expired. Expired entries are removed lazily: get, getOrPut, and remove treat them as absent, and purgeExpired sweeps them eagerly. size therefore includes expired entries that have not been swept yet.

When put inserts a new key while the cache holds maxSize entries, it first purges expired entries and then, if still full, evicts the least recently used live entry. get and a getOrPut hit refresh recency; replacing a key with put refreshes both recency and the entry's age.

Time is measured with the TimeSource.WithComparableMarks passed to the constructor, TimeSource.Monotonic by default.

This class is not thread-safe.

Type Parameters

K

the key type.

V

the value type.

Throws

if ttl is negative or maxSize is not positive.

Constructors

Link copied to clipboard
constructor(ttl: Duration, maxSize: Int = Int.MAX_VALUE, timeSource: TimeSource.WithComparableMarks = TimeSource.Monotonic)

Creates an empty cache with the given time-to-live, capacity, and time source.

Properties

Link copied to clipboard

The maximum number of entries the cache holds. Always positive.

Link copied to clipboard
val size: Int

The number of stored entries, including expired entries that have not been swept by purgeExpired or touched by another operation yet.

Link copied to clipboard

The time-to-live of each entry, measured from when it was stored.

Functions

Link copied to clipboard
fun clear()

Removes every entry from the cache, live or expired.

Link copied to clipboard
fun get(key: K): V?

Returns the value for key and marks it most recently used, or returns null if the key is absent or its entry has expired.

Link copied to clipboard
fun getOrPut(key: K, defaultValue: () -> V): V

Returns the live value for key if present, otherwise computes it with defaultValue, stores it through put, and returns it.

Link copied to clipboard

Removes every expired entry and returns how many were removed. Runs in time linear in size.

Link copied to clipboard
fun put(key: K, value: V)

Stores value under key with a fresh age and marks the entry most recently used.

Link copied to clipboard
fun remove(key: K): V?

Removes the entry for key and returns its value if it was still live, or returns null if the key is absent or its entry has expired.