Guava Study notes: Guava cache

Source: Internet
Author: User
Tags google guava

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:

    1. ImmutableMap<K, V> getAllPresent(Iterable<?> keys) Get cached values for multiple keys at once
    2. putAnd putAll methods to add one or more cache entries to the cache
    3. invalidateAnd invalidateAll methods to remove cache entries from the cache
    4. asMap()method to get a snapshot of the cached data ConcurrentMap<K, V>
    5. cleanUp()Empty cache
    6. refresh(Key)Refresh the cache, which is to cache the cached data and update the cache

Guava Study notes: Guava cache

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.