4
votes

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?

1
That code doesn't compile, does it? (.getFromCache())fge
Also, please specify a more specific exception than Exception in your CacheLoader; when you implement a method which throws something, you can change the exception thrown to any subclass of the given exception.fge
Yeah, I'm curious about the exception handling... if getKeyFromDatabase 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
I edited my post, adding exceptions. I stepped through getKeyFromDatabase() and load() and getFromCache(), there is no exception thrown, it is just loading from the database everytime.ddxue
I also tried setting an .expireAfterWrite(10, TimeUnit.MINUTES) in the builder and it still was hitting the load method everytime for the same key.ddxue

1 Answers

3
votes

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.