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

Caching

You can use this caching package to cache any user-defined values.

import ballerina/caching;
import ballerina/io;
import ballerina/runtime;
public function main (string[] args) {
    caching:Cache cache = new;

Create a new cache. Cache cleanup task runs every 5 seconds and clears any expired cache. So cache expiry time is set to 4 seconds to demonstrate cache cleaning.

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

Add a new entry to the cache.

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

Get the cached value.

    runtime:sleepCurrentWorker(6000);

Send the current worker to sleep mode for 6 seconds. No execution takes place during this period.

Since the cache expiry time is 4 seconds, the cache cleanup task runs at the 5th second and cleans the cache while this thread is sleeping. Now, this value is null.

    if (cache.hasKey("Name")){
        name = <string>cache.get("Name");
    } else {
        name = "";
    }
    io:println("Name: " + name);
}
$ ballerina run caching.bal
Name: Ballerina
Name: