ResidentModelCache

class ResidentModelCache(val budgetBytes: Long = Long.MAX_VALUE) : AutoCloseable(source)

In-memory cache of loaded models (engines or other AutoCloseable resources) with a RAM budget and OS low-memory eviction.

Resources are closed outside the internal lock, on the thread that triggered the eviction. Thread-safe.

Parameters

budgetBytes

resident budget in bytes.

Constructors

Link copied to clipboard
constructor(budgetBytes: Long = Long.MAX_VALUE)

Properties

Link copied to clipboard
Link copied to clipboard

Keys currently resident, least recently used first.

Link copied to clipboard

Sum of the estimated sizes of resident models.

Functions

Link copied to clipboard

Leases the model under key, or returns null if it is not resident.

Link copied to clipboard

Evicts on every signal from observer. Close the returned handle to unsubscribe.

Link copied to clipboard
open override fun close()

Closes every resident model, leased or not. Idempotent; the cache cannot be used afterwards.

Link copied to clipboard

Closes idle models according to level: NORMAL enforces the budget, MODERATE trims to half the budget (or half of what is resident if no budget is set), CRITICAL closes every idle model.

Link copied to clipboard
suspend fun <T : AutoCloseable> getOrPut(key: String, estimatedBytes: Long, loader: suspend () -> T): ModelLease<T>

Leases the model under key, loading it with loader if it is not resident. If another caller loaded the same key concurrently, the extra copy is closed and the resident one is returned.

Link copied to clipboard
fun <T : AutoCloseable> put(key: String, estimatedBytes: Long, resource: T): ModelLease<T>

Adds resource under key and returns a lease on it. A previous idle model under key is closed; if the previous one is leased, put fails. Then idle models are evicted until the budget holds.

Link copied to clipboard
fun remove(key: String): Boolean

Closes the idle model under key. Returns false if it is absent or leased.