suparnatural-cache / com.suparnatural.core.cache / Cache

Cache

interface Cache

A generic Cache. A cache can be backed by persistent stores. The main different between cache and a persistent store is that the latter is considered to be slower than the former. Therefore, the APIs to access objects from a persistent store are not the same as that of a cache. For example, in InMemoryCache vs DiskStore, the InMemoryCache is the primary data structure which other parts of the application should interact with while DiskStore can be used to rehydrate the cache after a cold start.

Therefore, avoid directly interacting with the store.

However, you can always create your own cache which persists objects by default without a backing store.

Properties

persistentStores

abstract val persistentStores: List<CacheStore>

List of persistent stores backing cache.

replacementPolicy

abstract val replacementPolicy: CacheReplacementPolicy

Cache replacement policy to create space when cache is full.

size

abstract val size: Int

Size of the cache

Functions

addObject

abstract fun <T : Cacheable> addObject(obj: T): Boolean

Adds a Cacheable object to the cache. The cache key is retrieved by calling Cacheable.cacheKey method.

getAllObjects

abstract fun getAllObjects(): List<Cacheable>

Returns a list of all the cached objects.

getObject

abstract fun <T : Cacheable> getObject(key: String): T?

Returns a object with the given key.

hashCode

abstract fun hashCode(key: String): Int

Returns a hash code for the given key. For example, it may wrap the raw hash code for a string by cache sizeUnsafe.

rehydrate

abstract fun rehydrate(): Unit

Rehydrates the cache by loading all the cached objects from the persisted stores. It does a total replacement of current cache with the objects loaded from persistent stores and does not perform a merge of any sort.

removeObject

abstract fun <T : Cacheable> removeObject(key: String): <ERROR CLASS><T?, Boolean>

Removed a Cacheable object from the cache.

Inheritors

InMemoryCache

abstract class InMemoryCache : Cache

An abstract, thread-safe in-memory cache with a custom HashTable implementation backed by an array of atomic values. It guarantees consistency in both single and multi-threaded environment.