Guava Cache Memory Example

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public class GuavaTest {

private static GuavaTest gt = new GuavaTest();

public static GuavaTest getInstance(){
return gt;
}
private LoadingCache<String,String> cache;

private GuavaTest() {

cache = CacheBuilder.newBuilder().refreshAfterWrite(2,TimeUnit.SECONDS).
build(new CacheLoader<String, String>(){

@Override
public String load(String arg0) throws Exception {
// TODO Auto-generated method stub
return addcache(arg0);
}

}
);
}

private String addcache(String arg0) {
System.out.println(“Adding Cache”);
return arg0.toUpperCase();
}
public String getEntry(String args) throws ExecutionException{
System.out.println(cache.size());
return cache.get(args);
}

public static void main(String[] args) {
GuavaTest gt = GuavaTest.getInstance();
try {
System.out.println(gt.getEntry(“java”));
System.out.println(gt.getEntry(“java”));
Thread.sleep(2100);
System.out.println(gt.getEntry(“java”));
System.out.println(gt.getEntry(“java”));

} catch (ExecutionException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}

}

Leave a Reply

Your email address will not be published. Required fields are marked *

82 − 81 =