Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using guava cache without a load function

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

like image 323
Mike W Avatar asked Nov 23 '12 16:11

Mike W


People also ask

Is Guava cache thread-safe?

Cache entries are manually added using get(Object, Callable) or put(Object, Object) , and are stored in the cache until either evicted or manually invalidated. Implementations of this interface are expected to be thread-safe, and can be safely accessed by multiple concurrent threads.

Is Guava cache persistent?

A Guava cache extension that allows caches to persist cache entries when they cannot longer be stored in memory.

Is Guava cache blocking?

A non-blocking cache implementation. Guava java library has an interface LoadingCache that has methods related with cache. The library also provides a CacheBuilder whose constructor needs a CacheLoader that has different methods to load values into the cache.


1 Answers

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

Cache<String, String> cache = CacheBuilder.newBuilder().build(); 
like image 50
JB Nizet Avatar answered Sep 28 '22 02:09

JB Nizet