Caching Empty Values

Problem

Your application is querying the database excessively only to find that there is no result. Since there is no result, there is nothing to cache. How do you prevent the query from being executed unnecessarily?

Solution

Cache a null value, signalling that a particular key doesn't exist.

Discussion

Ehcache supports null value caching. Simply cache a "null" value instead of a real value.

Use a maximum time to live setting in your cache settings to force a re-load every once in a while.

In code, this may look like:

public abstract class GenericDao<K, V extends BaseEntity> implements Dao<K, V>
{
    /* Here is the cache reference */
    protected EhcacheWrapper<K, V> cache;

    public V getById(final K id) 
    {
        V value;

        if ((value = cache.get(id)) == null) {
            value = this.jdbcTemplate.queryForObject(findById, mapper, id);

            // note we put the value, even if it's null
            cache.put(id, value);
        }
        return value;
    }
}

Note: This code makes use of the Ehcache Wrapper recipe.

And the ehcache.xml file may look like this (making sure to set the maximum time to live setting:

<cache
    name="some.cache.name"
    maxElementsInMemory="10000"
    eternal="false"
    timeToIdleSeconds="300"
    timeToLiveSeconds="600"
/>