Autumn 2015
Creation
Cache<String, Double> cache = CacheBuilder.newBuilder()
.maximumSize(10)
.recordStats()
.expireAfterWrite((long) 2.5, TimeUnit.MINUTES)
.build();
Use
if ((cache.getIfPresent(country)) != null) {
return cache.getIfPresent(country);
} else {
double val = gdp.getGDP(country)
cache.put(country, val);
return val;
}
(will still somehow work correct in this case, but with degraded performance)
Creation
Cache<String, Double> cache = CacheBuilder.newBuilder()
.maximumSize(10)
.expireAfterWrite(150, TimeUnit.SECONDS)
.build();
Use
Double val = cache.getIfPresent(countryCode);
if (val != null){
return val;
} else {
val = gdp.getGDP(countryCode);
cache.put(countryCode, val);
return val;
}
Creation
LoadingCache<CountryCode, GDP> cache = CacheBuilder.newBuilder()
.maximumSize(10)
.expireAfterAccess(150, TimeUnit.SECONDS)
.refreshAfterWrite(5, TimeUnit.MINUTES)
.build(new CacheLoader<CountryCode, GDP>() {
@Override
public GDP load(CountryCode code) throws Exception {
GDP gdp = gdpService.getGDP(code);
return gdp;
}
});
Use
final GDP gdp = cache.get(countryCode);