Guava Study notes: Guava cache
Reprint: Http://outofmemory.cn/java/guava/cache/how-to-use-guava-cache
There is a cache package in Google Guava, which provides memory caching capabilities. There are many issues to be considered in memory caching, including concurrency issues, cache invalidation mechanisms, cache release when memory is insufficient, cache hit ratios, cache removal, and so on. Of course, these things are guava in mind.
Using caching in guava requires declaring a Cachebuilder object, setting the cache's related parameters, and then calling its build method to get an instance of the cache interface. Take a look at the following code and comments, and note that each parameter of the cache is specified in the note.
Public Static voidMain(String[]Args) Throws Executionexception, Interruptedexception{Cache interface This is Loadingcache,loadingcache. The cache can be loaded automatically when the cache entry does not existLoadingcache<Integer,Student>StudentcacheThe Cachebuilder constructor is private and can be used only by its static method Newbuilder () to obtain an instance of Cachebuilder= Cachebuilder.Newbuilder()Set the concurrency level to 8, and the concurrency level is the number of threads that can write the cache at the same time.Concurrencylevel(8)8 seconds after setting write cache expires.Expireafterwrite(8, Timeunit.SECONDS) Set the initial capacity of the cache container to 10.Initialcapacity(10)Setting a maximum cache size of 100, more than 100, removes cache entries according to LRU's most recent use of algorithms.MaximumSize(100)Set the hit ratio to count the cache.Recordstats()Set the cache removal notification.Removallistener(New Removallistener<Object, Object> () {@OverridePublic voidOnremoval(Removalnotification<Object, Object>Notification) {System.Out.println(Notification.GetKey() + "was removed, cause" +Notification.Getcause());}})The build method can specify cacheloader to automatically load the cache when the cache does not exist by Cacheloader implementation.Build(New Cacheloader<Integer, Student> () {@OverridePublic StudentLoad(IntegerKey) Throws Exception {System.Out.println("Load Student" +Key);StudentStudent= New Student();Student.SetId(Key);Student.SetName("Name" +Key);ReturnStudent;}});For (IntI=0;I<20;I++) {To get the data from the cache, we need to load the cached data via Cacheloader because we have not set the cacheStudentStudent=Studentcache.Get(1);System.Out.println(Student);Sleep 1 secondsTimeunit.SECONDS.Sleep(1); } system.. Println "cache stats:" //last print cache hit rate etc system.. Println (studentcache. Stats (). Tostring }
The output of the above program is as follows:
Load Student1Student{Id=1,Name=Name1}Student{Id=1,Name=Name1}Student{Id=1,Name=Name1}Student{Id=1,Name=Name1}Student{Id=1,Name=Name1}Student{Id=1,Name=Name1}Student{Id=1,Name=Name1}Student{Id=1,Name=Name1}1was removed,CauseIsExpiredload Student1......Student{Id=1,Name=Name1}Student{Id=1,Name=Name1}Student{Id=1,Name=Name1}Student{Id=1, Name=name 1} cache stats:cachestats {hitcount=17 Misscount=3, Loadsuccesscount=3, loadexceptioncount< Span class= "pun" >=0, Totalloadtime=1348802, Evictioncount=2< Span class= "pun" >
See in 20 this loop hit Count is 17 times, Miss 3 times, this is because we set the cache expiration time is written 8 seconds, so 20 seconds will expire two times, and the first time the cache is also no value, so will miss 3 times, others hit.
The guava memory cache is very powerful and can be set up with a variety of options and is lightweight and easy to use. In addition, the following methods are available to facilitate various needs:
ImmutableMap<K, V> getAllPresent(Iterable<?> keys)
Get cached values for multiple keys at once
put
And putAll
methods to add one or more cache entries to the cache
invalidate
And invalidateAll
methods to remove cache entries from the cache
asMap()
method to get a snapshot of the cached data ConcurrentMap<K, V>
cleanUp()
Empty cache
refresh(Key)
Refresh the cache, which is to cache the cached data and update the cache
Guava Study notes: Guava cache