I'm using the Guava LoadingCache to store results from database queries. However, despite not setting an eviction policy, doing a get on the cache through getFromCache() results in my debug point in the CacheLoader load() method being hit every time, therefore also resulting a debug point in the database query method getKeyFromDatabase() being hit every time.
Here is my code:
private final LoadingCache<String, QueryResult> cache;
public MyDao() {
cache = CacheBuilder.newBuilder()
.maximumSize(40)
.build(new CacheLoader<String, QueryResult>() {
@Override
public QueryResult load(String key) throws DatabaseException {
return getKeyFromDatabase(key);
}
});
}
public QueryResult getFromCache(String key) throws DatabaseException {
try {
return cache.get(key);
} catch (ExecutionException e) {
throw new DatabaseException(e);
}
}
private QueryResult getKeyFromDatabase(String key) throws DatabaseException {
try {
...
return new QueryResult();
} catch (SQLException e) {
throw new DatabaseException(e);
}
}
Am I missing something obvious here?
Alright false alarm guys, guava is not actually broken (surprise surprise). The reason is cause the code that was instantiating the DAO was instantiating a new object every time, so a new cache was also instantiated every time. I made the cache a static variable and it now works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.