Embracing the Messiness in Search of Epic Solutions

Guava: Elegant Caching Mechanisms

Posted

in

There are many different ways to implement a caching mechanism. Google’s Guava provides very simple and elegant solutions to do so.

OPTION 1: Caching using Supplier

If you want to cache just one thing, Supplier should satisfy that requirement.

private Supplier<Collection<Person>> allEmployeesCache = Suppliers.memoizeWithExpiration(
        new Supplier<Collection<Person>>() {
            public Collection<Person> get() {
                return makeExpensiveCallToGetAllEmployees();
            }
        }, 1, TimeUnit.DAYS);


public Collection<Person> getAllEmployees() {
    return allEmployeesCache.get();
}

In the above example, we cache all employees for a day.

OPTION 2: Caching using LoadingCache

If you want to cache multiple things (ex: think Hashmap-like), LoadingCache should satisfy that requirement.

private LoadingCache<String, Collection<Person>> employeeRoleLoadingCache = CacheBuilder.newBuilder()
        .expireAfterWrite(1, TimeUnit.DAYS)
        .maximumSize(1000)
        .build(new CacheLoader<String, Collection<Person>>() {
            @Override
            public Collection<Person> load(String roleName) throws Exception {
                return makeExpensiveCallToGetAllEmployeesByRoleName(roleName);
            }
        });
                
public Collection<Person> getAllEmployeesByRole(String roleName) {
    return employeeRoleLoadingCache.getUnchecked(roleName);
}

In the above example, we cache all employees for each given role for a day. Further, we configure the cache to store up to 1000 elements before evicting the older cached element.

Tags:

Comments

Leave a Reply