import ballerina/cache;
import ballerina/io;
import ballerina/runtime;public function main() {
    cache:Cache cache = new(4000);
    cache.put("Name", "Ballerina");
    string name = "";
    if (cache.hasKey("Name")){
        name = <string>cache.get("Name");
    }
    io:println("Name: " + name);
    runtime:sleep(6000);
    if (cache.hasKey("Name")){
        name = <string>cache.get("Name");
    } else {
        name = "";
    }
    io:println("Name: " + name);
}

Caching

The caching module caches all user-defined values.

import ballerina/cache;
import ballerina/io;
import ballerina/runtime;
public function main() {
    cache:Cache cache = new(4000);

This creates a new cache. The cache cleanup task runs every 5 seconds and clears all the expired caches. In this example, the cache expiry time is set to four seconds in order to demonstrate how cache cleaning is carried out.

    cache.put("Name", "Ballerina");

Adds a new entry to the cache.

    string name = "";
    if (cache.hasKey("Name")){
        name = <string>cache.get("Name");
    }
    io:println("Name: " + name);

Fetches the cached value.

    runtime:sleep(6000);

This sends the current worker to the sleep mode for six seconds. No execution takes place during this period.

    if (cache.hasKey("Name")){
        name = <string>cache.get("Name");
    } else {
        name = "";
    }
    io:println("Name: " + name);
}

The cache expires after 4 seconds. The cache cleanup task runs during the fifth second and cleans the cache while this thread is in the sleep mode. As a result, the value in the cache becomes null.

# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `ballerina run` command.
$ ballerina run cache.bal
Name: Ballerina
Name: