Java Dynamic Cache growth Milestones (i)--Create a simple cache

Source: Internet
Author: User

In the actual project, we often need to use the cache. In general, the cache medium is memory, while the common DB stores the data on the hard disk, the cache reads are electrical pulses, and the hard disk reads mechanically to read the rotating hard drive, the speed difference is hundreds of times. Therefore, it is often possible to access the data that is often used through caching to improve speed.

Creating a cache is really about two objects, 1. The cache object, which is a cached object; 2. The CacheManager object, an object that manages different caches, is essentially a map that is used to save and retrieve different caches.

The simplest cache implementation is as follows:

/** *  Project Name: *  File Description: Create a cache manager <span style= "Font-family:arial, Helvetica, Sans-serif;" > Liu Morning </span> *  Main Features: *  version Number: 1.0 *  creation time: 2013-12-3 **/package nboffer;import Java.util.HashMap; public class CacheManager {static hashmap<string,cache> cachemap=new hashmap<string,cache> ();p ublic Static Cache GetCache (String ID) {return cachemap.get (ID);} public static void Putcache (cache cache) {Cachemap.put (cache.id, cache);} public static void Main (string[] args) {cache cache1=new cache ("1", "A1"); Cache Cache2=new Cache ("2", "A2"); Cachemanager.putcache (CACHE1); Cachemanager.putcache (CACHE2); Cachemanager.getcache ("1"). Showinfo ();}} Class cache{string id;//equivalent to primary Key object Val;public cache (String ID) {New cache (id,null);} Public Cache (String id,object val) {this.id=id;this.val=val;} public void SetValue (Object val) {this.val=val;} public void Showinfo () {System.out.println ("The ID of the cache is:"   +id+ "The value of the   cache is:   " +val);}}


Question 1: Which step can reflect the advantages of caching relative to the direct read library?

The GetCache () method is actually read from the HashMap, which is read from the JVM and is in memory.


Question 2: If the cache fails to hit, does it return an empty cached cache?

Yes, so we need to improve the GetCache, failed to hit the description of the cache does not have, need to take a number from the database.


/** * Project Name: * File Description: Create a cache manager <span style= "Font-family:arial, Helvetica, Sans-serif;" > Liu Morning </span> * Main Features: * Version number: 1.0 * Creation time: 2013-12-3 **/package Nboffer;import java.util.hashmap;public class Cachem Anager {static hashmap<string,cache> cachemap=new hashmap<string,cache> ();p ublic static Cache GetCache ( String ID) {if (Cachemap.get (ID) ==null) {Object val=getfromdb (ID); Cachemap.put (ID, new Cache (Id,val));} return Cachemap.get (ID);} public static void Putcache (cache cache) {Cachemap.put (cache.id, cache);} public static Object Getfromdb (String id) {SYSTEM.OUT.PRINTLN ("reads slowly from memory id=" +id+ "corresponding data ... "); return new String (" value "+id);} public static void Main (string[] args) {cache cache1=new cache ("1", "value1"); Cache Cache2=new Cache ("2", "value2"); Cachemanager.putcache (CACHE1); Cachemanager.putcache (CACHE2); Cachemanager.getcache ("3"). Showinfo ();}} Class cache{string id;//equivalent to primary Key object Val;public cache (String ID) {New cache (id,null);} Public Cache (String id,object val) {this.id=id;this.val=vAl;} public void SetValue (Object val) {this.val=val;} public void Showinfo () {System.out.println ("The ID of the cache is:" +id+ "The value of the cache is:" +val);}}


Question 3: What should I do if I want to refresh the cache for a while, for example, every 15min refresh of all caches?

For ease of observation, we set the refresh to 1s per interval.

/** * Project Name: * File Description: Create a cache manager Liu Morning * Main Features: * Version number: 1.0 * Creation time: 2013-12-3 **/package nboffer;import Java.util.hashmap;impor T Java.util.iterator;import Java.util.set;public class CacheManager {static hashmap<string,cache> cacheMap=new Hashmap<string,cache> ();p ublic static Cache GetCache (String ID) {if (Cachemap.get (ID) ==null) {Object val= Getfromdb (ID); Cachemap.put (ID, new Cache (Id,val));} return Cachemap.get (ID);} public static void Putcache (cache cache) {Cachemap.put (cache.id, cache);} public static Object Getfromdb (String id) {SYSTEM.OUT.PRINTLN ("reads slowly from memory id=" +id+ "corresponding data ... "); return new String (" value "+id);} public static void Refreshcaches () {System.out.println ("flush cache ... "); Set<string> Keyset=cachemap.keyset (); Iterator it=keyset.iterator (); while (It.hasnext ()) {string id= (String) It.next (); Object Val=getfromdb (ID); Cachemap.put (ID, new Cache (Id,val));}} public static void Main (string[] args) {cache cache1=new cache ("1", "value1"); Cache Cache2=new Cache ("2", "value2"); Cachemanager.putcacHe (CACHE1); Cachemanager.putcache (CACHE2); Cachemanager.getcache ("3"). Showinfo (); Thread Refreshtd=new thread () {public void run () {while (true) {refreshcaches (); try {thread.sleep (1000);//refresh} catch every second (Interruptedexception e) {E.printstacktrace ();}}}; Refreshtd.start ();}} Class cache{string id;//equivalent to primary Key object Val;public cache (String ID) {New cache (id,null);} Public Cache (String id,object val) {this.id=id;this.val=val;} public void SetValue (Object val) {this.val=val;} public void Showinfo () {System.out.println ("The ID of the cache is:" +id+ "The value of the cache is:" +val);}}

Question 4: The above you said the cache is a problem, because every time you are unified refresh, some of the data just in 14min59s when uploaded, you have to let it refresh after 1s? In addition, some data changes quickly, not 15min refresh, but need not 1min refresh once, you do this really good? Also, some data will not be used within the 15min, and it is necessary to refresh it?

The above three questions do need to be improved, so I can target different caches and refresh them when they are free (send request + cache does not exist/fail) and then optimize. The code is as follows:

/** * Project Name: * File Description: Create a cache manager LCX * Main Features: * Version number: 1.0 * Creation time: 2013-12-3 **/package nboffer;import Java.util.date;import J Ava.util.hashmap;public class CacheManager {static hashmap<string,cache> cachemap=new Hashmap<string,cache > ();p ublic static cache GetCache (String ID) {//For non-existent or stale caches uniformly handled if (Cachemap.get (ID) ==null| |! Cachemap.get (ID). IsValid ()) {Object val=getfromdb (ID); Cache cache=new Cache (id,val); cache.latest=new Date (); Cachemap.put (ID, cache);} return Cachemap.get (ID);} public static void Putcache (cache cache) {cache.latest=new Date (); Cachemap.put (cache.id, cache);} public static Object Getfromdb (String id) {SYSTEM.OUT.PRINTLN ("reads slowly from memory id=" +id+ "corresponding data ... "); return new String (" value "+id);} public static void Main (string[] args) {cache cache1=new cache ("1", "value1"); Cache Cache2=new Cache ("2", "value2"), cache2.invalidtime=5000;//setting the failure angle is 5scachemanager.putcache (CACHE1); Cachemanager.putcache (cache2); try {thread.sleep (6000);} catch (Interruptedexception e) {e.printstacktrace ();} CachemaNager.getcache ("1"); Cachemanager.getcache ("2");}} Class cache{string id;//equivalent to primary Key object Val;date latest;//Recent refresh time long invalidtime=10000;//default failure time 10spublic Cache (String ID) {New Cache (id,null);} Public Cache (String id,object val) {this.id=id;this.val=val;} public void SetValue (Object val) {this.val=val;} /** * Determine if the cache is now valid * @return */public boolean isValid () {return (new Date ()). GetTime ()-latest.gettime () <invalidtime;} public void Showinfo () {System.out.println ("The ID of the cache is:" +id+ "The value of the cache is:" +val);}}

Question 5: Now that we have done this, a few nouns about caching have to be said.

Cache Hit ratio: Cache hit ratio = read from cache/(cache reading + disk reading).

Cache invalidation: The cache has exceeded the expiration time. Expired (and there may be other reasons).

Cache penetration: For data that does not exist, each time you want to send a request to DB, the risk to the DB is very great.

Cache avalanche: A large amount of access to a failed cache over a short period of time can cause db downtime.

Cache algorithm: LRU, LFU, LIFO


The next section will look at different caching algorithms.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Dynamic Cache growth Milestones (i)--Create a simple cache

Related Article

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.