Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Google Guava CacheBuilder example
import com.google.common.cache.*;
import java.util.BitSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class Test {
private LoadingCache<String, BitSet> cache = null;
RemovalListener<String, BitSet> removalListener = new RemovalListener<String, BitSet>() {
public void onRemoval(RemovalNotification<String, BitSet> removal) {
BitSet b = removal.getValue();
// to something
System.out.println("Removing the key = " + removal.getKey());
}
};
public Test(){
this.cache = CacheBuilder.newBuilder()
//.maximumSize(10000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.softValues()
.removalListener(removalListener)
.build(
new CacheLoader<String, BitSet>() {
public BitSet load(String key) throws Exception {
return loadBitset(key);
}
});
}
private BitSet loadBitset(String key) {
return new BitSet(1000000);
}
public static void main(String argv[]) throws ExecutionException, InterruptedException {
Test t = new Test();
// Thread.sleep(10000);
System.out.println("1 = " + t.cache.size());
for (int i = 0; i < 2000 ; i++) {
t.cache.get(String.valueOf(i));
}
System.out.println("2 = " + t.cache.size());
// Thread.sleep(10000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.