Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

guava

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.

like image 692
Gili Avatar asked Sep 30 '11 21:09

Gili


1 Answers

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).

like image 76
maaartinus Avatar answered Oct 08 '22 17:10

maaartinus