ballerina/cache module

Module Overview

This module offers a cache that supports time-based eviction, and size-based eviction. This means that entries are removed from the cache once the expiry time has elapsed (i.e., time-based eviction), or when the cache runs out of space (i.e., size-based eviction). Caching is useful when a value takes significant cost or time to compute and retrieve, and it is therefore useful to cache it for future use.

Sample

The following sample creates a cache that can hold a maximum of 10 entries. An entry of this cache expires one minute after its last access. When the cache is full, 20% of the entries (i.e., 2 entries) will be evicted to make space for new entries.

// The `evictionFactor` specifies the percentage of items
// that will be evicted when the cache is full.
cache:Cache cache = new(capacity = 10, expiryTimeMillis = 60000, evictionFactor = 0.2);

// Enter a value, and a key to reference that value.
// This will be a new entry in the cache.
cache.put("key-a", "value-a");

// Use the same key to retrieve the value.
string returnValue = <string>cache.get("key-a");

Module Detail

Objects

Object Description
Cache

Represents a cache.

public type Cache object

Represents a cache.

  • <Cache> __init(int expiryTimeMillis, int capacity, float evictionFactor)

    Parameter Name Data Type Default Value Description
    expiryTimeMillis int 900000
    capacity int 100
    evictionFactor float 0.25
  • <Cache> hasKey(string key) returns (boolean)

    Checks whether the given key has an accociated cache value.

    Parameter Name Data Type Default Value Description
    key string
    Return Type Description
    boolean

    True if the given key has an associated value, false otherwise.

  • <Cache> size() returns (int)

    Returns the size of the cache.

    Return Type Description
    int

    The size of the cache

  • <Cache> put(string key, any value)

    Adds the given key, value pair to the provided cache.

    Parameter Name Data Type Default Value Description
    key string

    value which should be used as the key

    value any

    value to be cached

  • <Cache> get(string key) returns (any)

    Returns the cached value associated with the given key. If the provided cache key is not found, () will be returned.

    Parameter Name Data Type Default Value Description
    key string

    key which is used to retrieve the cached value

    Return Type Description
    any

    The cached value associated with the given key

  • <Cache> remove(string key)

    Removes a cached value from a cache.

    Parameter Name Data Type Default Value Description
    key string

    key of the cache entry which needs to be removed

  • <Cache> keys() returns (string[])

    Returns all keys from current cache.

    Return Type Description
    string[]

    all keys