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?
.getFromCache()
) – fgeException
in yourCacheLoader
; when you implement a method which throws something, you can change the exception thrown to any subclass of the given exception. – fgegetKeyFromDatabase
throws an exception every time and that fact is being hidden from you somehow, it's going to have to keep trying to load again every time. – ColinD