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.