Skip to main content

Google Guava Cache for caching

google guava logo
Sometimes we have to deal with computing power (complex calculation) or network latency (database call). By caching this complex calculation or network calls, it will be helpful to improve the performance. This post is about the Google Guava that can be used for caching. Guava cache stores key and value.

These are major configurations.

  • concurrencyLevel(int concurrencyLevel) – allowed concurrency level among update operations.
  • expireAfterAccess(long duration, TimeUnit unit) – entry is expired after accessing.
  • expireAfterWrite(long duration, TimeUnit unit) – entry is expired after modifying.
  • maximumSize(long size) – maximum no of entries in the cache.
  • removalListener(RemovalListener<? super K1,? super V1> listener) – notify when entry is removed in the cache.

Google Guava Cache API

1.) Create a maven project.

2.) Add Google Guava dependency.

3.) Create a Customer domain model. It includes customer id and customer name.

4.) Create a CustomerRepo.java. It works as a database in this example.

5.) Create a CustomerCacheProvider.java. It decides whether to take it from cache or database.

6.) In this class show how to use the caching. When calling the first time, it takes from the database and cache it. The Second time, it takes from the cache.

output:


Related Post

1753total visits,8visits today

RSS
Follow by Email
Facebook
Facebook
Google+
http://mydevgeek.com/google-guava-cache-caching
Twitter