(translated) Google guava Cache

Source: Internet
Author: User
Tags memcached google guava

Translated from Google Guava Cache

This Post was a continuation of my series on Google guava, this time covering guava Cache. Guava Cache offers more flexibility and power than either a HashMap or concurrenthashmap, but was not as heavy as using EHC Ache or Memcached (or robust for the matter, as guava Cache operates solely in memory). The Cache interface has methods your would expect to see like ' Get ', and ' invalidate '. A method you won ' t find was ' put ', because guava Cache is ' self-populating ', values for aren ' t present when requested was fetched or calculated, then stored. This means a ' get ' call would never return null. In all fairness, the previous statement are not%100 accurate. There is another method ' Asmap ' this exposes the entries in the cache as a thread safe map. Using ' Asmap ' would result in does have any of the-the-loading operations performed, so calls to ' get ' would return null I f The value is not present. Although this was a post about guava Cache, I am going to spend the bulk of the time Talking about Cacheloader and Cachebuilder. Cacheloader specifies how to load values, and Cachebuilder are used to set the desired features and actually build the Cach E.

This article is a continuation of my Google Guava series, this time with the theme guava Cache. Guava Cahce is more flexible and powerful than HashMap and Concurrenthashmap, but it's not as heavy as using Ehcache or memcached (so it's not as robust as it is because the guava cache only operates in memory). Guava cache has the interface you expect, like ' get ', and ' invalide '. A method you will not find is ' put ' because the guava cache is "self-populated", and values that are not present at the time of the request are crawled or calculated and then stored. So the ' get ' method never returns NULL. To be fair, the above sentence is not 100% accurate. There is also a method called ' Asmap ', exposing the entries in the cache as a thread-safe map. Using ' Asmap ' does not perform any self-padding, so calling ' get ' will return NULL if the value does not exist (what is the point of doing so?). Although this blog is about guava cache, I also spend a lot of time talking about Cacheloader and Cachebuilder. Cacheloader is used to indicate how the value is loaded, and Cachebuilder is used to set the attribute you want and is actually used to create the cache.

Cacheloader

Cacheloader is a abstract class that specifies what to calculate or load values, if not present. There is ways to the Create an instance of a Cacheloader:

    1. Extend the Cacheloader<k,v> class

    2. Use the static factory method Cacheloader.from

Cacheloader is an abstract class used to indicate how to calculate or load a value, if not found (if not in the cache). There are two ways to create an instance of Cacheloader:

    1. Extended Cacheloader<k,v> Class
    2. Using static engineering methods Cacheloader.from

If you extend Cacheloader your need V load(K key) to override the method, instructing how to generate the value for a given key. Using the static CacheLoader.from method you build a cacheloader either by supplying a Function or Supplier interface. When supplying a function object, the function was applied to the key to calculate or retrieve the results. Using a Supplier interface The value is obtained independent of the key.

If you extend Cacheloader, you need to override the V-load method to show how to generate value from a specified key. When you use the static Cacheloader.from method to construct Cacheloader, you either provide a function interface or supplier interface ("object that implements the function or supplier interface"). When a function object is provided, this function is used to calculate or obtain the result based on key. When using a supplier interface, the acquisition of value does not relate to key.

Cachebuilder

The cachebuilder is used to construct cache instances. It uses the fluent style of building and gives you the option of setting the following properties on the cache:

    • Cache Size Limit (removals use a LRU algorithm)

    • Wrapping keys in weakreferences (strong references used by default for keys)

    • Wrapping values in either WeakReferences or softreferences (strong references used by default)

    • Time to expire entires after last access

    • Time based expiration of entries after being written or updated

    • Setting a removallistener that can recieve events once an entry be removed from the cache

    • Concurrency level of the cache (defaults to 4)

Cachebuilder is used to create a cache instance, which is the instance of the cache. It uses the fluent style (that is, the. xx (). XX (). XX () mode) to create so that you can specify the following properties of the cache:

    • Cache size Limit (' Remove ' is using the LRU algorithm)
    • Whether to package keys as WeakReference (the default for key is to use strong reference (weak and strong references to Java))
    • Wrap values in WeakReference or softreference (default use strong reference)
    • How long after this entry expires (expire) after the last access to an entry (note: entry, which is the kv pair in the cache)
    • How long this entry expires after the write or update
    • Set a Removallistener, after an entry expires, this removallistener is used to receive the event ("which entry" expired, this event)
    • The concurrency of the cache (default is 4)

The concurrency level option was used to partition, the table internally such that updates can occur without contention. The ideal setting would is the maximum number of threads that could potentially access the cache at one time. Here's an example of a possible usage scenario for guava Cache.

The concurrency selection is used to partition the internal tables (the table used to store entries internally when the cache is implemented) so that updates can be made without competition. The ideal setting is the number of threads that may have access to the cache at the same time. Here's a scenario where you might use the guava cache

 Public classPersonsearchserviceimplImplementsSearchservice<list<person>> { PublicPersonsearchserviceimpl (Samplelucenesearcher lucenesearcher, Sampledbservice dbservice) { This. Lucenesearcher =Lucenesearcher;  This. Dbservice =Dbservice;    Buildcache (); } @Override PublicList<person> Search (String query)throwsException {returncache.get (query); }    Private voidBuildcache () {Cache= Cachebuilder.newbuilder (). Expireafterwrite (10, Timeunit.minutes). MaximumSize (1000). Build (NewCacheloader<string, list<person>>() {@Override Publiclist<person> load (String querykey)throwsException {List<String> ids =Lucenesearcher.search (Querykey); returnDbservice.getpersonsbyid (IDS);    }                }); }}

In this example, I am setting the cache entries to expire after minutes of being written or updated in the cache, with A maximum amount of $ entires. Note the usage of Cacheloader on line 15.

In this example, I set the cache entry to expire after 10 minutes of writing or updating, and the maximum number is 1000. Note the example of the Cacheloader in line 15th

Removallistener

The removallistener will receive notification of an item being removed from the cache. These notifications could is from manual invalidations or from a automatic one due to time expiration or garbage collectio N. The removallistener<k,v> parameters can is set to listen for specific type. To receive notifications for any key or value set them to use Object. It should be noted here, a removallistener would receive a Removalnotification<k,v> object that implements the Ma P.entry interface. The key or value could is null if either has already been garbage collected. Also the key and value object is strong references, regardless of the type of references used by the cache.

Removallistener is notified when an entry is removed from the cache. This notification may be due to manually invalidating entries or automatically removing entries due to time expiration or garbage collection. The type parameter of the removallistener<k,v> can be set to listen for the specified type. If you want to receive any of the KV notifications, set them to object. It is necessary to note that Removallistener receives an object of type removalnotification<k,v>, which implements the Map.entry interface. If key or value is garbage collected, then key and value may be null. And the key and value objects are strong reference, regardless of the type of reference in the cache.

Cachestats

There is also a very useful class cachestats so can be retrieved via a call to Cache.stats (). The Cachestats object can give insight into the effectiveness and performance of your caches by providing statistics such a S

There is a very useful object for the Cachestats class, which can be obtained using cache.status (). The Cachestats object gives you an insight into the efficiency and performance of your cache by giving you the following statistics.

    • Hit count hits total

    • Miss Count Misses total

    • Total load Time

    • Total requests number of requests

Cachestats provides many other counts in addition to the ones listed above.

In addition to the statistical results listed above, CacheStatus also provides a number of other values.

Conclusion

The guava Cache presents some very compelling functionality. The decision to use a guava Cache really comes down to the tradeoff between memory availability/usage versus increases in Performance. I have added a unit test cachetest demonstrating the usages discussed here. As Alway comments and suggestions are welcomed. Thanks for your time.

Guavacache offers some very competitive features. Using the guava cache stems from a tradeoff between available/used memory and performance. I added a unit test to show the usage of the discussion here. As usual, welcome comments and suggestions. Thank you for your time.

(translated) Google 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.