1

I'm trying to get this cache to refresh every day at 3AM. The problem is that users are having to wait a long time for the cache to warm up. So I would rather it be refreshed overnight and be ready to quickly access in the morning for the UI.

    return CacheBuilder.newBuilder()
            .maximumSize(1000)
            .expireAfterAccess(1, TimeUnit.DAYS)
            .build(new CacheLoader<String, Long>() {
                @Override
                public Long load(String key)
                        throws Exception {
                        return db.getMetrics(key);
                }
            });

I want to be able to provide a fixed set of keys in the cache to refresh at 3AM.

I read the Google documentation but it seems like that only refreshes data that's already been loaded in the cache.

TL;DR - Looking to warm up the cache with a fixed set of keys at a specific time during the day

Ramie
  • 1,171
  • 2
  • 16
  • 35
  • Generally you'd have a background thread scheduled to prefetch data, but often that exceeds the size of a local cache. In that case you would instead warm up a remote caching tier (e.g. memcached) which makes local cache misses inexpensive. – Ben Manes Dec 15 '15 at 01:11

1 Answers1

1

From what I can tell Guava doesn't have anything built-in to "freshen"/"warm" values for a set of keys at some scheduled time but you can easily do it on your own.

Warming the Cache

You can warm your cash by simply calling getAll(Iterable) on your LoadingCache<String, Long> instance. e.g.

loadingCache.getAll(keysToFreshen);

Where keysToFreshen is an instance of Iterable<String> containing the keys you want to freshen at 3 AM (or whenever) (e.g. a Set<String>).

Running the Cache Warming Code with a Job/Task Scheduler

You now simply need to run loadingCache.getAll(keysToFreshen) using a tool to schedule a job/task at 3AM. You can use Quartz, Spring, Java's ScheduledExecutorService (see here for an example), etc.

Community
  • 1
  • 1
mfulton26
  • 29,956
  • 6
  • 64
  • 88