Java Dynamic cache Growth (i)--Create a simple cache

Source: Internet
Author: User

In the actual project, we often need to use the cache. In general, the cached media is memory, while the common DB stores the data on the hard disk, the cache read is an electrical pulse, and the hard drive reads mechanically to read the rotating hard drive, and the speed difference is a hundredfold. So it is often possible to use the cache to access the data often used to improve speed.

Creating a cache is actually targeted at two objects, 1. Cache object, that 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 caching implementation is as follows:

/** * Project Name: * File Description: Create a cache manager <span style= "Font-family:arial, Helvetica, Sans-serif;"

></span> * Main Features: * Version number: 1.0 * Create time: 2013-12-3 **/package nboffer;

Import Java.util.HashMap;
	
	public class CacheManager {static hashmap<string,cache> cachemap=new hashmap<string,cache> ();
	public 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 ();
	The class Cache {String id;//corresponds to the 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 () ID of cache is: "+id+"  The cache value 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, it is returned to the empty cache.

Yes, so we need to improve on the GetCache, failed to hit the description of the cache, need to fetch from the database.


/** * Project Name: * File Description: Create a cache manager <span style= "Font-family:arial, Helvetica, Sans-serif;"

></span> * Main Features: * Version number: 1.0 * Create time: 2013-12-3 **/package nboffer;

Import Java.util.HashMap;
	
	public class CacheManager {static hashmap<string,cache> cachemap=new hashmap<string,cache> ();
			public 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); The public static Object Getfromdb (String id) {SYSTEM.OUT.PRINTLN ("slowly reads id=" +id+ "Data from memory ...)	
	");
	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 ();
	The class Cache {String id;//corresponds to the 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 ("Cache ID is:" +id+ "cache value is:" +val);
 }
}


Question 3: What should I do if I want to refresh the cache for a period of time, such as flushing all the caches every 15min.

To facilitate observation, we set the 1s refresh once per interval.

/** * Project Name: * File Description: Create a cache Manager * Main Features: * Version number: 1.0 * Create time: 2013-12-3 **/package nboffer;
Import Java.util.HashMap;
Import Java.util.Iterator;

Import Java.util.Set;
	
	public class CacheManager {static hashmap<string,cache> cachemap=new hashmap<string,cache> ();
			public 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); The public static Object Getfromdb (String id) {SYSTEM.OUT.PRINTLN ("slowly reads id=" +id+ "Data from memory ...)	
	");
	return new String ("value" +id); public static void Refreshcaches () {System.out.println ("Refresh 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);//Every second refresh} catch (Interruptedexception e) {e.printstacktrace ();
		}
				}
			}
		};
	Refreshtd.start ();
	
	The class Cache {String id;//corresponds to the 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 ("Cache ID is:" +id+ "cache value is:" +val);
 }
}

Question 4: Above you say the cache is a problem, because each time you are unified refresh, some data just in the 14min59s upload, you have to let it in 1s after the refresh. In addition, some data changes quickly, not 15min refresh, but need not 1min refresh once, you do really good. Also, some data is not used in this 15min, it is necessary to refresh it.

The above three questions do need to be improved, so I can target different caches, and then refresh them when the free need (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 * Create time: 2013-12-3 **/package nboffer;
Import Java.util.Date;

Import Java.util.HashMap;

	public class CacheManager {static hashmap<string,cache> cachemap=new hashmap<string,cache> (); The public static cache GetCache (String ID) {//Is uniformly processing if (Cachemap.get (ID) ==null| |! for non-existent or invalid caching
			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); The public static Object Getfromdb (String id) {SYSTEM.OUT.PRINTLN ("slowly reads id=" +id+ "Data from memory ...)	
		");
	return new String ("value" +id);
		public static void Main (string[] args) {cache cache1=new cache ("1", "value1");
		Cache Cache2=new Cache ("2", "value2");
		The cache2.invalidtime=5000;//setting failure angle is 5s Cachemanager.putcache (CACHE1); Cachemanager.putcaChe (cache2);
		try {thread.sleep (6000);
		catch (Interruptedexception e) {e.printstacktrace ();
		} cachemanager.getcache ("1");
	Cachemanager.getcache ("2");
	The class Cache {String id;//corresponds to the primary key Object Val;
	Date latest;//Recent Refresh time long invalidtime=10000;//default expiration Time 10s 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; /** * To determine if the cache is now valid * @return/public boolean isValid () {return (new Date ()). GetTime ()-latest.gettime () <i
	Nvalidtime;
	public void Showinfo () {System.out.println ("Cache ID is:" +id+ "cache value is:" +val);
 }
}

Question 5: Now that we have done this, we have to say a few words about caching.

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

Cache expiration: Cache exceeded expiration time. Expired (and may have other causes).

Cache penetration: For nonexistent data, every time you want DB to send a request, the damage to DB is very great.

Cache avalanche: For a cached cache to be heavily accessed over a short period of time, it can cause db downtime.

Caching algorithms: LRU, LFU, LIFO


The next section will look at different caching algorithms.



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.