Gili Gili - 1 year ago 93
Java Question

How to put() values into Guava's Cache class?

I'm a little confused by CacheBuilder and Cache introduced in Guava 10. The documentation hints that it's possible to overwrite values but as far as I can tell, Cache does not contain any methods for doing so. Any ideas?

I'm trying to construct a Map that expires a key 10 seconds after it was last read or written-to. When a value is looked up, I expect the previously-set value to be returned, or a default value to be computed if none exists.

Answer Source

AFAIK, not yet. But there's a thread mentioning that Cache.asMap.put is planned for release 11.

I'd say the current state of the Javadoc is a remnant if the CacheBuilder's evolution from the MapMaker (where the cache-setting method are currently deprecated).

I'm trying to construct a Map that expires a key 10 seconds after it was last read or written-to. When a value is looked up, I expect the previously-set value to be returned, or a default value to be computed if none exists.

Using expireAfterAccess(10, TimeUnit.SECONDS) will keep an entry alive for 10 seconds after any access to it. And the only values you'll get are those computed by your CacheLoader (either earlier or during get).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download