emon
1/8/2020 - 9:55 AM

Java Guava Memoization

import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.TimeUnit;

public class CostlySupplier {
    //Memoize example for key value pairs type <String, String>

    //1-Rename the old SLOW function (for example adding  _InnerSlowFunction to its old name)
    static public String getIt_InnerSlowFunction(final String key) {
        System.out.println("slow computation/io...");
        //time waste to emulate computing...
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {

        }

        //here you put the slow computation / io
        String strResult = "Resource for " + key + " from access : " + key.length();
        return strResult;
    }

    //2- Replace the original function for this one, the "cached" version
    static public String getIt(final String key) {
        return CACHE_TO_MEMOIZE.getUnchecked(key);
    }

    //3- Create the static cache (it can be the step 1, but is here for pedagogical purposes )
    private static final LoadingCache<String, String> CACHE_TO_MEMOIZE = CacheBuilder.newBuilder()
            .expireAfterWrite(5, TimeUnit.SECONDS)// timeout for valid data expiration
            .build(CacheLoader.from(CostlySupplier::getIt_InnerSlowFunction)); //function reference

    /**
     * Main test example
     */
    public static void main(String args[]) throws InterruptedException {
        System.out.println("get " + getIt("key AA"));
        System.out.println("get " + getIt("key BB"));

        //From now on return cache without doing the slow function call..for 5 seconds
        System.out.println("get " + getIt("key AA"));
        System.out.println("get " + getIt("key BB"));
        System.out.println("get " + getIt("key AA"));
        System.out.println("get " + getIt("key BB"));

        System.out.println("Waiting...");

        Thread.sleep(6000);//wait some time

        //Now, cache is gone, we need to go slow again..
        System.out.println("get " + getIt("Key AA"));
        System.out.println("get " + getIt("Key BB"));
    }
}