Implementation of caching cache mechanism in Java _java

Source: Internet
Author: User

caching is the memory of an object that is often invoked by a program or system, and can be invoked quickly when it is used, without having to create a new duplicate instance. This can reduce system overhead and improve system efficiency.

Caching can be divided into two major categories:

First, through file caching, as the name implies file caching refers to the storage of data on disk, whether you are in XML format, serialized file dat format or other file format;

Second, the memory cache, that is, the implementation of a class static map, the map for the regular additions and deletions check.

Import java.util.*; Description: Manage cache//Extensible functionality: When Chche to memory overflow, some of the earliest cache objects must be purged, which requires the Save creation time public class CacheManager {Private stat for each cached object. 

 IC HashMap cachemap = new HashMap (); 
 Single instance construction method private CacheManager () {super (); 
  //Gets the cached public static Boolean Getsimpleflag (String key) of the Boolean value try{return (Boolean) Cachemap.get (key); 
  }catch (NullPointerException e) {return false; 
  public static long Getserverstartdt (String key) {try {return (long) cachemap.get (key); 
  catch (Exception ex) {return 0; The cache public synchronized static Boolean Setsimpleflag (String Key,boolean flag) {if (flag && get) of a Boolean value is set 
  Simpleflag (key)) {//If True is not allowed to be overwritten return false; 
   }else{cachemap.put (key, flag); 
  return true; } public synchronized static Boolean Setsimpleflag (String key,long Serverbegrundt) {if (Cachemap.get (key) = null 
   ) {cachemap.put (Key,serverbegrundt); 
  return true; 
  }else{return false; 
 }}//Get cached. 
 Synchronous static method private synchronized static Cache GetCache (String key) {return (Cache) cachemap.get (key); 
 //Determine if there is a cache private synchronized static Boolean Hascache (String key) {return Cachemap.containskey (key); 
 //Clear all cached public synchronized static void ClearAll () {cachemap.clear (); //clear a certain class of cache by traversing all objects under HashMap to determine whether its key matches the incoming type public synchronized static void ClearAll (String type) {Itera 
  Tor i = Cachemap.entryset (). iterator (); 
  String key; 
  ArrayList arr = new ArrayList (); 
    try {while (I.hasnext ()) {Java.util.Map.Entry Entry = (java.util.Map.Entry) i.next (); 
    Key = (String) entry.getkey (); 
    if (Key.startswith (type)) {//If the match is deleted arr.add (key); 
   for (int k = 0; k < arr.size (); k++) {clearonly (Arr.get (k)); 
  } catch (Exception ex) {ex.printstacktrace (); 
 }//Clear the specified cache public synchronized static void Clearonly (String key) {cachemap.remove (key); 
}//Load Cache Public synchronized static void Putcache (String key, Cache obj) {cachemap.put (key, obj); 
   //Get cached information public static cache Getcacheinfo (String key) {if (Hascache (key)) {Cache cache = GetCache (key); 
   if (cacheexpired (cache)) {//call to determine whether to terminate the method cache.setexpired (true); 
  return cache; 
 }else return null; //Load cache information public static void Putcacheinfo (String key, Cache obj, long Dt,boolean expired) {Cache cache = new Cac 
  He (); 
  Cache.setkey (key); Cache.settimeout (dt + system.currenttimemillis ()); 
  Set how long to update the cache cache.setvalue (obj); cache.setexpired (expired); 
 Cache default load, termination status is False Cachemap.put (key, cache); 
  //Overrides Load cache information method public static void Putcacheinfo (String key,cache obj,long dt) {Cache cache = new cache (); 
  Cache.setkey (key); 
  Cache.settimeout (Dt+system.currenttimemillis ()); 
  Cache.setvalue (obj); 
  Cache.setexpired (FALSE); 
 Cachemap.put (Key,cache); }//To determine if caching terminates public static Boolean cacheexpired (cache cache) {
  if (null = cache) {//incoming buffer does not exist return false; Long NOWDT = System.currenttimemillis (); The current number of milliseconds in the system is long Cachedt = Cache.gettimeout (); The number of expired milliseconds in the cache if (Cachedt <= 0| | 
  CACHEDT&GT;NOWDT) {///expires at less than or equal to zero, or false to False if the expiration time is greater than the current time; 
  else {//greater than the expiration time is expired return true; 
 }//Get the size of the cache public static int getcachesize () {return cachemap.size (); 
  //Gets the size of the specified type public static int getcachesize (String type) {int k = 0; 
  Iterator i = Cachemap.entryset (). iterator (); 
  String key; 
    try {while (I.hasnext ()) {Java.util.Map.Entry Entry = (java.util.Map.Entry) i.next (); 
    Key = (String) entry.getkey (); 
    if (Key.indexof (type)!=-1) {///If the match is removed k++; 
  A catch (Exception ex) {ex.printstacktrace ()); 
 } return k; 
  }//Get all key-value names in cached objects public static ArrayList Getcacheallkey () {ArrayList a = new ArrayList (); 
   try {iterator i = Cachemap.entryset (). iterator (); while (I.hasnext ()) { 
    Java.util.Map.Entry Entry = (java.util.Map.Entry) i.next (); 
   A.add ((String) Entry.getkey ()); 
  The catch (Exception ex) {} finally {return A; 
  }//Get the key-value name of the specified type in the cache object public static ArrayList Getcachelistkey (String type) {ArrayList a = new ArrayList (); 
  String key; 
   try {iterator i = Cachemap.entryset (). iterator (); 
    while (I.hasnext ()) {Java.util.Map.Entry Entry = (java.util.Map.Entry) i.next (); 
    Key = (String) entry.getkey (); 
    if (Key.indexof (type)!=-1) {A.add (key); 
  The catch (Exception ex) {} finally {return A; 

}} package Lhm.hcy.guge.frameset.cache;  public class Cache {Private String key;//cache ID Private Object value;//cache data Private Long timeout;//update time private Boolean expired; 
  Whether to terminate public Cache () {super (); 
    Public Cache (String key, Object value, Long TimeOut, Boolean expired) {This.key = key; 
    This.value = value; 
  This.timeout = TimeOut;  this.expired = expired; 
  Public String Getkey () {return key; 
  Public long GetTimeout () {return timeOut; 
  Public Object GetValue () {return value; 
  public void Setkey (string string) {key = string; 
  public void settimeout (long l) {timeOut = l; 
  public void SetValue (object) {value = object; 
  public boolean isexpired () {return expired; 
  } public void Setexpired (Boolean b) {expired = B; }///test class, class test {public static void main (string[] args) {System.out.println (Cachemanager.getsimpleflag ("a 
LKSD ")); 
Cachemanager.putcache ("ABC", New Cache ()); 
Cachemanager.putcache ("Def", New Cache ()); 
Cachemanager.putcache ("CCC", New Cache ()); 
Cachemanager.clearonly (""); 
Cache C = new cache (); 
for (int i = 0; i < i++) {//Cachemanager.putcache ("" + I, c); 
}//Cachemanager.putcache ("Aaaaaaaa", c); Cachemanager.putcache ("ABCHCY;ALSKD ", c); 
Cachemanager.putcache ("CCCCCCCC", c); 
Cachemanager.putcache ("Abcoqiwhcy", c); 
System.out.println ("Before delete size:" +cachemanager.getcachesize ()); 
Cachemanager.getcacheallkey (); 
Cachemanager.clearall ("AAAA"); 
System.out.println ("Deleted Size:" +cachemanager.getcachesize ()); 


 Cachemanager.getcacheallkey ();
 } 
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.