[Design optimization]-use cache to improve program performance

Source: Internet
Author: User

Cache(Cache) is used to store data.Memory space. The main function is to temporarily store data processing results and provide the next access.

Cache is widely used. For example, browsers cache pages locally to reduce the number of http accesses. For example, when developing a server system, the designer adds cache for some core APIs to increase the system cache time.

The simplest cache implementation can be usedHashmap. Of course, this will cause many problems, such as when to clear invalid data and how to prevent memory overflow caused by too much cached data. A better solution is to useWeakhashmapUse Weak references to maintain a hash table and clear data when the memory is insufficient.

But as the most professional implementation, we should have a professional cache framework. For exampleEhcacheOscache and jbosscache. The ehcache cache comes from Hibernate and is the default data cache solution of the Hibernate framework. Oscache is designed by opensympthony and can be used to cache any objects, even some JSP pages or HTTP requests; jbosscache is a cache framework developed by JBoss for data sharing between JBoss clusters.

Next, we will take ehcache as an example to briefly introduce the basic usage of cache.

First of all, we need to download the ehcache package in the official website http://ehcache.org, after the download is complete, add the jar package under the Lib folder to the project can be used.



After the jar package is introduced, create a file named ehcache. xml under the classpath path of the project, as shown in the following content:

<?xml version="1.0" encoding="UTF-8"?><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"    monitoring="autodetect" dynamicConfig="true">    <diskStore path="data/ehcache" />    <defaultCache maxEntriesLocalHeap="10000" eternal="false"        timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"        maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"        memoryStoreEvictionPolicy="LRU">        <persistence strategy="localTempSwap" />    </defaultCache>    <cache name="sampleCache1" maxEntriesLocalHeap="10000"        maxEntriesLocalDisk="1000" eternal="false" diskSpoolBufferSizeMB="20"        timeToIdleSeconds="300" timeToLiveSeconds="600"        memoryStoreEvictionPolicy="LFU" transactionalMode="off">        <persistence strategy="localTempSwap" />    </cache>    <cache name="sampleCache2" maxEntriesLocalHeap="1000" eternal="true"        memoryStoreEvictionPolicy="FIFO" /></ehcache>

The preceding configuration file first configures a default cache template. When the ehcache interface is used in a program to dynamically generate a cache, these parameters are used to define a new cache. Then, two caches are defined, named samplecache1 and samplecache2 respectively.

The main parameters and meanings in the configuration file are as follows:

Required attributesThere are 3,

Maxentrieslocalheap: Maximum number of cache objects in the heap memory. If the value is 0, there is no limit.

Maxentrieslocaldisk: Maximum number of objects in the disk. The default value is 0.

Eternal: whether elements is permanently valid. If it is true, timeouts will be ignored and the element will never expire.

Below isOptional attributes

Timetoidleseconds: the number of idle seconds before expiration. This attribute is valid only when eternal is false. 0 is unlimited.

Timetoliveseconds: the number of seconds before expiration. The interval from creation time to expiration time is the survival time. When eternal is false, this attribute is valid. 0 is unlimited.

Diskspoolbuffersizemb: this parameter sets the cache size of diskstore (disk cache. The default value is 30 mb. Each cache should have its own buffer.

Clearonflush: When flush () is called to clear the cache, the default value is

Memorystoreevictionpolicy: Memory recycle policy. Default recycle policy: Least recent use of least recently used, first-in-first-out, and less frequently used. Localtempswap is switched to the disk when the number of caches is large.

Timetoidleseconds: If the cache is not permanently stored, it is removed if no entry is accessed within the specified time range of timetoidleseconds.

Diskpersistent: whether the entries in the disk are permanently saved

Diskexpirythreadintervalseconds: interval at which cache cleanup threads run

Transactionalmode: sets the transaction mode of the cache action.

Then we use the pre-defined cache in the Java program.

Package BUPT. xiaoye. charpter2.ehcache; import net. SF. ehcache. cache; import net. SF. ehcache. cachemanager; import net. SF. ehcache. element; public class ehcachetest {public static void main (string [] ARGs) throws interruptedexception {cachemanager manager = cachemanager. create (); // retrieve all cachename string Names [] = manager. getcachenames (); system. out. println ("---- All cache names ----"); For (INT I = 0; I <n Ames. length; I ++) {system. out. println (Names [I]);} system. out. println ("----------------------"); // obtain a cache object cache cache1 = manager. getcache (Names [0]); // Add the cache cache1.put (new element ("key1", "values1") to the cache1 object ")); element element = cache1.get ("key1"); // read the cache system. out. println ("key1 \ t =" + element. getobjectvalue (); // manually create a cache (defaultcache must exist in ehcache, and "test" can be changed to any value) cache cache2 = new C AchE ("test", 1, true, false, 2, 3); manager. addcache (cache2); cache2.put (new element ("Jimmy", "Yang Guo under the bodhi tree"); // deliberately stops for 1.5 seconds to verify whether the thread has expired. sleep (1500); element elejimmy = cache2.get ("Jimmy"); // 1.5 s <2 s will not expire if (elejimmy! = NULL) {system. out. println ("Jimmy \ t =" + elejimmy. getobjectvalue ();} // wait for another 0.5 s, total duration: 1.5 + 0.5> = min (2, 3), expired thread. sleep (500); elejimmy = cache2.get ("Jimmy"); If (elejimmy = NULL) {system. out. println ("Jimmy \ t = NULL");} // retrieve a nonexistent cache item system. out. println ("fake \ t =" + cache2.get ("fake"); manager. shutdown ();}}

For ehcache, we can also write a simple tool class to perform various operations for ehcache.

package bupt.xiaoye.charpter2.ehcache;import java.io.Serializable;import net.sf.ehcache.CacheException;import net.sf.ehcache.CacheManager;import net.sf.ehcache.Element;public class EHCacheUtil {private static CacheManager manager;static {try {manager = CacheManager.create();} catch (CacheException e) {e.printStackTrace();}}public static void put(String cachename, Serializable key,Serializable value) {manager.getCache(cachename).put(new Element(key, value));}public static Object get(String cachename, Serializable key) {try {Element e = manager.getCache(cachename).get(key);if (e == null)return null;return e.getObjectValue();} catch (IllegalStateException e) {e.printStackTrace();}return null;}}

With the above tools, you can easily use ehcache in actual work.

When adding methods to the cache, you can use the original encoding method to construct a key based on the input parameters, and then cache the results. The advantage of this implementation method is that the Code is straightforward and simple. The disadvantage is that the Code in the cache is closely coupled with the business-Layer Code, and the dependency is strong.

The following describes the dynamic proxy-based Cache solution. The biggest benefit of a dynamic proxy-based Cache solution is that the cache operation code is completely independent and isolated at the business layer without the need to focus on Cache operations, adding cache to a new function method does not affect the implementation of the original method. It is a flexible software structure.

The biggest benefit is:Code without modifying a logical methodYou can add the cache function for it to improve its efficiency.

Assume that the following method is used to break down an integer. Create a dynamic proxy for this class and test the performance of both:

Package BUPT. xiaoye. charpter2.ehcache; import Java. io. serializable; import Java. lang. reflect. method; import net. SF. cglib. proxy. enhancer; import net. SF. cglib. proxy. methodinterceptor; import net. SF. cglib. proxy. methodproxy; Class heavymethoddemo {Public String heavymethod (INT num) throws exception {stringbuffer sb = new stringbuffer (); // do something whith numthread. sleep (20); return sb. tostring () ;}} public class implements methodinterceptor {heavymethoddemo real = new heavymethoddemo (); @ overridepublic object intercept (Object arg0, method arg1, object [] arg2, methodproxy arg3) throws throwable {string v = (string) ehcacheutil. get ("samplecache1", (serializable) arg2 [0]); If (V = NULL) {v = real. heavymethod (integer) arg2 [0]); ehcacheutil. put ("samplecache1", (integer) arg2 [0], V);} return NULL ;} /*** proxy class with cache function * @ return */public static heavymethoddemo newcachedheavymethod () {enhancer = new enhancer (); enhancer. setsuperclass (heavymethoddemo. class); enhancer. setcallback (New cglibheavymethodinterceptor (); heavymethoddemo cglibproxy = (heavymethoddemo) enhancer. create (); Return cglibproxy;}/*** subject without cache function * @ return */public static heavymethoddemo newheavymethod () {return New heavymethoddemo ();} public static void main (string [] ARGs) throws exception {heavymethoddemo M = newcachedheavymethod (); long begin = system. currenttimemillis (); For (INT I = 0; I <100; I ++) {M. heavymethod (21474586);} system. out. println (system. currenttimemillis ()-begin); M = newheavymethod (); begin = system. currenttimemillis (); For (INT I = 0; I <100; I ++) {M. heavymethod (21474586);} system. out. println (system. currenttimemillis ()-begin );}}

Tested, it takes time to use the cache 1144 MS. Time consumed when no cache is used 2152 Ms.




[Design optimization]-use cache to improve program performance

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.