Gili
Gili

Reputation: 89993

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.

NOTE: This question is outdated. Although the above Javadoc shows the existence of a Cache.put(K key, V value) method, it not exist when the question was first posted.

Upvotes: 11

Views: 4455

Answers (2)

maaartinus
maaartinus

Reputation: 46382

Since long, there's Cache#asMap returning a ConcurrentMap view.

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

I'd say the current old 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).

Upvotes: 6

Niraj Tolia
Niraj Tolia

Reputation: 541

Minor update. Cache.asMap().put() should show up in Guava 10.1 sometime during the first week of October, 2011. See this thread for more info.

Upvotes: 3

Related Questions