Skip to content

Instantly share code, notes, and snippets.

@hernaneche
Last active August 5, 2016 15:09
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.util.concurrent.TimeUnit;
public class MemoizeGuava {
//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(MemoizeGuava::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"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment