Skip to content

Instantly share code, notes, and snippets.

@jordanlewis
Created June 27, 2012 02:20
Show Gist options
  • Save jordanlewis/3000913 to your computer and use it in GitHub Desktop.
Save jordanlewis/3000913 to your computer and use it in GitHub Desktop.
Weight-based cache eviction
public class CacheTest {
private Logger logger = LoggerFactory.getLogger(CacheTest.class);
public AtomicInteger numEvicted = new AtomicInteger(0);
private final LoadingCache<String, Integer> testCache = CacheBuilder.newBuilder()
.maximumWeight(10)
.weigher(new Weigher<String, Integer>() {
@Override
public int weigh(String key, Integer value) {
return key.length();
}
})
.removalListener(new RemovalListener<String, Integer>() {
@Override
public void onRemoval(RemovalNotification<String, Integer> notification) {
logger.info("Removed entry {}->{} with weight {}: {}", new Object[]{
notification.getKey(), notification.getValue(),
notification.getKey().length(), notification.getCause()});
numEvicted.incrementAndGet();
}
})
.build(new CacheLoader<String, Integer>() {
@Override
public Integer load(String key) throws Exception {
return key.length();
}
});
@Test
public void testWeightedCache() throws ExecutionException {
testCache.get("aaaaa");
testCache.get("bbbb");
assertEquals(2, testCache.size());
assertEquals(0, numEvicted.get());
testCache.get("blah");
assertEquals(2, testCache.size());
assertEquals(1, numEvicted.get());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment