javaguava

Persist guava cache on shutdown


I use the following guava cache to store messages for a specific time waiting for a possible response. So I use the cache more like a timeout for messages:

Cache cache = CacheBuilder.newBuilder().expireAfterWrite(7, TimeUnit.DAYS).build();
cache.put(id,message);
...
cache.getIfPresent(id);

In the end I need to persist the messages with its currently 'timeout' information on shutdown and restore it on startup with the internal already expired times per entry. I couldn't find any methods which give me access to the time information, so I can handle it by myself.

The gauva wiki says:

Your application will not need to store more data than what would fit in RAM. (Guava caches are local to a single run of your application. They do not store data in files, or on outside servers. If this does not fit your needs, consider a tool like Memcached.)

Do you think this restriction address also a 'timeout' map to persist on shutdown?


Solution

  • I don't believe there's any way to recreate the cache with per-entry expiration values -- even if you do use reflection. You might be able to simulate it by using a DelayedQueue in a separate thread that explicitly invalidates entries that should have expired, but that's the best I think you can do.

    That said, if you're just interested in peeking at the expiration information, I would recommend wrapping your cache values in a class that remembers the expiration time, so you can look up the expiration time for an entry just by looking up its value and calling a getExpirationTime() method or what have you.

    That approach, at least, should not break with new Guava releases.