43

My java app has a cache, and I'd like to swap out the current cache implementation and replace it with the guava cache.

Unfortunately, my app's cache usage doesn't seem to match the way that guava's caches seem to work. All I want is to be able to create an empty cache, read an item from the cache using a "get" method, and store an item in the cache with a "put" method. I do NOT want the "get" call to be trying to add an item to the cache.

It seems that the LoadingCache class has the get and put methods that I need. But I'm having trouble figuring out how to create the cache without providing a "load" function.

My first attempt was this:

LoadingCache<String, String> CACHE = CacheBuilder.newBuilder().build(); 

But that causes this compiler error: incompatible types; no instance(s) of type variable(s) K1,V1 exist so that Cache conforms to LoadingCache

Apparently I have to pass in a CacheLoader that has a "load" method.

(I guess I could create a CacheLoader that has a "load" method that just throws an Exception, but that seems kind of weird and inefficient. Is that the right thing to do?)

3
  • I'd be tempted to say that (from what information you've posted), it doesn't sound hugely like it's a cache as opposed to just being a Map. Commented Nov 23, 2012 at 17:15
  • 3
    @Sean Parsons: IMHO the more important difference between Cache and Map is that the former may forget things anytime. The loading is an additional feature. Commented Nov 23, 2012 at 17:19
  • I was more trying to elucidate if it actually was a cache. Commented Nov 24, 2012 at 9:53

1 Answer 1

58

CacheBuilder.build() returns a non-loading cache. Just what you want. Just use

Cache<String, String> cache = CacheBuilder.newBuilder().build(); 
Sign up to request clarification or add additional context in comments.

4 Comments

For me it shows compile time error. it could not convert from <object,object> to <string,string> generic. I am using this lib for android.
@CreativeManix You have to use Cache class not LoadingCache.
wish that Google would explain this in the documentation - the only examples they give are LoadingCache.
(edited previous comment). You can then use .getIfPresent(Object key) to retrieve stuff without providing a loader.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.