A Comparison of local caches (1) "Native cache comparison (1)"

Source: Internet
Author: User
Tags try catch

1. Spring Local Cache "Spring locally cached"

Spring provided cacheable annotation since 3.1. It ' s very super convinient to use and can obviously boost application performance.

Starting with version 3.1, Spring provides cacheable annotations. It is very convenient to use and can significantly improve application performance. Specific, how to use it?

First, create a cache bean.

First, create a cache bean. Here, we set a local cache of three seconds (3 seconds after write expires).

@Bean
Public Cache Ephemeralcache () {
return new Concurrentmapcache (Ephemeral_cache, Cachebuilder.newbuilder ()
. Expireafterwrite (3, Timeunit.seconds)
. Build (). Asmap (), false);
}

Second, add @Cacheable to the existed method.

Next, add @cacheable annotations to the existing methods that you want to use the cache

@Cacheable (cachenames = appcacheconfig.ephemeral_cache, key = "{#root. MethodName, ' test '}")
Public Integer GenID () {
int i = Ai.incrementandget ();
System.out.println (String.Format ("Populate cache%s", Localdatetime.now ()));
return i;
}

Finally, enjoy!

Then, enjoy the joy of caching!

Executorservice exe = Executors.newworkstealingpool ();
Exe.submit ((), {
while (true) {
Cacheapi.genid ();
Thread.Sleep (50);
}
});

See output of below codes

The following log matches the original cache settings exactly

2017-06-08 10:17:49.990  INFO 12460---[           main] com.loops.nbs.Application for                 7.973  2017-06-08t10:17:52.3722017-06-08t10:17:55.3792017-06-08t10:17:58.3872017-06-08t10 : 18:01.3942017-06-08t10:18:04.4022017-06-08t10:18:07.4092017-06-08t10:18:10.417  2017-06-08t10:18:13.426

2. Guava caches "guava local cache"

Guava is a set of libraries provided by Google. In memory cache are part of it.

Guava is a set of tools provided by Google. Only the caching section is discussed here.

 Public classGuavacacheexample {StaticCache<integer, integer> cache =Cachebuilder.newbuilder (). Expireafterwrite (2, Timeunit.seconds). Recordstats (). build (); StaticLoadingcache<integer, integer> Loadingcache =Cachebuilder.newbuilder (). Expireafterwrite (2, Timeunit.seconds). Build (NewCacheloader<integer, integer>() {@Override PublicInteger load (integer key)throwsException {System.out.println ("Populate Cache"); returnKey * 10;    }            }); StaticScheduledexecutorservice Scheduler = Executors.newscheduledthreadpool (1);  Public Static voidMain (string[] args)throwsException {usenormalcache (); }    Static voidUsenormalcache ()throwsException {scheduler.schedulewithfixeddelay ()System.out.println (Cache.stats ()), 0, 1, Timeunit.seconds);  for(inti = 0; I < 10; i++) {System.out.println (Cache.get (0, (){Thread.Sleep (500); return10;            })); Thread.Sleep (300); }    }    Static voidUseloadingcache ()throwsException { for(inti = 0; I < 10; i++) {System.out.println (Loadingcache.get (1)); Thread.Sleep (300); }    }}

Usually, there is 2 types of caches

1) Cache

Cache is basic usage, it provides method to get and put cache.

The cache is the base usage and provides the get and put operations.

2) Loadingcache

Loading cache requires a cacheloader when the cache is created. Every time when cache is expired or nonexisted, the load method would be called automatically and generate cache.

So user doesn ' t has to manually put the cache back after the cache is expired.

The Loading cache needs to be given a cacheloader when it is created. If the cache expires or does not exist, the Cacheloader load method is called and the cache is generated. This way, users don't have to care about outdated cache entries.

Besides, we can add recordstats () when creating a cache object. Later we can monitor the cache usage by calling Cache.stats ()

The Cache is created twice during the test, correspondingly, Totalloadtime (mesured in nano seconds) changed twice.

In addition to this, we can also use Recordstats to record cache usage when creating the cache. Then use the stats () method of the cache to observe.

During the test, our cache was generated 2 times, and Totalloadtime (nanoseconds) is a good proof of this.

Cachestats{hitcount=0, Misscount=0, loadsuccesscount=0, loadexceptioncount=0, totalloadtime=0, EvictionCount=0} 1010cachestats{hitcount=1, Misscount=1, Loadsuccesscount=1, loadexceptioncount=0, totalloadtime= 502324777, Evictioncount=0}101010cachestats{hitcount=4, Misscount=1, Loadsuccesscount=1, Loadexceptioncount=0, totalloadtime=502324777, evictioncount=0}1010cachestats{hitcount= 6, Misscount=1, Loadsuccesscount=1, loadexceptioncount=0, totalloadtime=502324777, Evictioncount=1}101010 cachestats{hitcount=8, misscount=2, loadsuccesscount=2, loadexceptioncount=0, totalloadtime=1002802169, Evictioncount=1}

3. Caffeine caches "caffeine local cache"

Caffeine cache is a optimized cache for Java 8. It has similar APIs to guava but provide higher performance, which makes it easy to migrate from Gauva to caffeine.

See this report for more details Https://github.com/ben-manes/caffeine/wiki/Benchmarks

The caffeine cache is intended for Java 8. The use of guava is much like (it is easy to migrate), but it performs better in multithreaded situations. It has a running link that compares the performance of various local caches.

 Public classCaffeinecacheexample {StaticCache<integer, integer> cache = caffeine. Newbuilder (). Expireafterwrite (2, Timeunit.seconds). Recordstats (). build (); StaticLoadingcache<integer, integer> Loadingcache = caffeine. Newbuilder (). Expireafterwrite (2, Timeunit.seconds). Build (NewCacheloader<integer, integer>() {@Override PublicInteger load (integer key)throwsException {System.out.println ("Populate Cache"); returnKey * 10;    }            }); StaticScheduledexecutorservice Scheduler = Executors.newscheduledthreadpool (1);  Public Static voidMain (string[] args)throwsException {usenormalcache (); }    Static voidUsenormalcache ()throwsException {scheduler.schedulewithfixeddelay ()System.out.println (Cache.stats ()), 0, 1, Timeunit.seconds);  for(inti = 0; I < 10; i++) {System.out.println (Cache.get (0, K- {                Try{Thread.Sleep (500); } Catch(Interruptedexception ex) {//Ignore                }                return10;            })); Thread.Sleep (300); }    }    Static voidUseloadingcache ()throwsException { for(inti = 0; I < 10; i++) {System.out.println (Loadingcache.get (1)); Thread.Sleep (300); }    }}

There exists slight difference between guava and caffeine

There's a little bit of difference in use.

1) Builder:guava use Cachebuilder to the Create new Builder while the caffeine use caffeine.

When you create a builder, guava uses cachebuilder and caffeine uses caffeine

2) Get Method:guava Pass callable for Get method

The Get method for both of the second parameter is slightly different guava incoming callable, the inside can throw an exception, without writing redundant try catch, and caffeine into the function, you must manually catch possible exceptions

extends throws Executionexception;

Caffeine pass Function for Get method

@CheckForNull    V Get (@Nonnull K var1, @Nonnull FunctionSuperextends v> var2);

Callable itself throws exception so we don ' t has to try catch the exception in the block while Function tolerates no exce Ption.

  @FunctionalInterface  public  interface  callable<v> { /**   * computes a result, or throws an exception if unable to doing so.  * *   @return   computed result *   @throws   Exception if unable to compute a result  
   
    */ 
      Throws   Exception;}  
   
@FunctionalInterface  Public Interface Function<t, r> {    /**     * applies this function to the given argument.     *     @param  t the function argument     @return the function result      */     R apply (t t);

Next Chapter, I ' ll compare the async cache.

In the next section, the blogger will further compare the asynchronous cache

A Comparison of local caches (1) "Native cache comparison (1)"

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.