Implementation of cache caching mechanism used in Java

Source: Internet
Author: User
Tags object object

    缓存,就是将程序或系统经常要调用的对象存在内存中,一遍其使用时可以快速调用,不必再去创建新的重复的实例。这样做可以减少系统开销,提高系统效率。    缓存主要可分为二大类:    一、通过文件缓存,顾名思义文件缓存是指把数据存储在磁盘上,不管你是以XML格式,序列化文件DAT格式还是其它文件格式;     
Importjava.util.*;//description: Managing caching //extensible functionality: when chche to memory overflow, you must erase some of the earliest cache objects, which requires that you save the creation time for each cached object public  class CacheManager {     Private StaticHashMap Cachemap =NewHashMap ();//single Instance Construction method    Private CacheManager() {Super(); }//get the cache of Boolean values     public Static Boolean Getsimpleflag(String Key) {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; }     }//set the cache for Boolean values     public synchronized Static Boolean Setsimpleflag(String key,BooleanFlag) {if(flag && Getsimpleflag (key)) {//if It is not allowed to be overwritten            return false; }Else{cachemap.put (key, flag);return true; }     } public synchronized Static Boolean Setsimpleflag(String key,LongServerbegrundt) {if(cachemap.get (key) = =NULL) {cachemap.put (key,serverbegrundt);return true; }Else{return false; }     }//get Cached. Synchronous static Methods    Private synchronized StaticCacheGetCache(String Key) {return(Cache) Cachemap.get (key); }//determine If a cache exists    Private synchronized Static Boolean Hascache(String Key) {returnCachemap.containskey (key); }//clear All caches     public synchronized Static void ClearAll() {cachemap.clear (); }//clears A particular type of cache by traversing all objects under HashMap to determine if its key matches the incoming type     public synchronized Static void ClearAll(String Type)         {Iterator i = cachemap.entryset (). Iterator ();         String key; ArrayList arr =NewArrayList ();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 droppedArr.add (key); }             } for(intK =0; K < Arr.size ();             K++) {clearonly (arr.get (k)); }         }Catch(Exception Ex)         {ex.printstacktrace (); }     }//clears 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 Cache Information     public StaticCacheGetcacheinfo(String Key) {if(hascache (key)) {cache cache = GetCache (key);if(cacheexpired (cache)) {//call to determine whether to terminate the methodCache.setexpired (true); }returnCache }Else             return NULL; }//load Cache Information     public Static void Putcacheinfo(String key, Cache obj,LongDtBooleanExpired) {cache cache =NewCache ();         Cache.setkey (key); Cache.settimeout (dt + system.currenttimemillis ());//set How long after the cache is updatedCache.setvalue (obj); Cache.setexpired (expired);//cache is loaded by default and the termination status is FalseCachemap.put (key, cache); }//override Load Cache information Method     public Static void Putcacheinfo(String Key,cache obj,LongDt) {cache cache =NewCache ();         Cache.setkey (key);         Cache.settimeout (dt+system.currenttimemillis ());         Cache.setvalue (obj); Cache.setexpired (false);     Cachemap.put (key,cache); }//determine If the cache is terminated     public Static Boolean cacheexpired(cache Cache) {if(NULL= = Cache) {//the incoming cache does not exist            return false; }LongNOWDT = System.currenttimemillis ();//system Current number of milliseconds        LongCachedt = Cache.gettimeout ();//number of expired milliseconds in cache        if(cachedt <=0|| Cachedt>nowdt) {//the expiration time is less than or equal to zero, or false if the expiration time is greater than the current time            return false; }Else{//greater than expiration time expires            return true; }     }//get the size in the cache     public Static int getcachesize() {returnCachemap.size (); }//gets the size of the specified type     public Static int getcachesize(String Type) {intK =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 droppedk++; }             }         }Catch(Exception Ex)         {ex.printstacktrace (); }returnK }//get all Key-value names in the cache object     public StaticArrayListGetcacheallkey() {ArrayList A =NewArrayList ();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 ()); }         }Catch(Exception Ex) {}finally{returnA }     }//gets The key value name of the specified type in the cache object     public StaticArrayListGetcachelistkey(String Type) {ArrayList A =NewArrayList (); 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); }             }         }Catch(Exception Ex) {}finally{returnA }     } } packagelhm.hcy.guge.frameset.cache; public  class Cache {         PrivateString key;//cache ID        PrivateObject value;//cache Data        Private LongtimeOut;//update Time        Private BooleanExpired//whether Termination         public Cache() {Super(); } public Cache(String key, Object value,LongtimeOut,BooleanExpired) { this. Key = key; this. Value = value; this. Timeout = timeout; this. expired = expired; } publicStringGetKey() {returnKey } public Long GetTimeout() {returntimeOut; } publicObjectGetValue() {returnValue } public void Setkey(string String)         {key = string; } public void SetTimeOut(LongL) {timeOut = l; } public void SetValue(object Object)         {value = object; } public Boolean isexpired() {returnExpired } public void setexpired(BooleanB) {expired = b; } }//test class,Class Test { public Static void Main(string[] Args) {System.out.println (cachemanager.getsimpleflag ("alksd"));//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 ("size before deletion:" +cachemanager.getcachesize ());//cachemanager.getcacheallkey ();//cachemanager.clearall ("aaaa");//System.out.println ("size after deletion:" +cachemanager.getcachesize ());//cachemanager.getcacheallkey ();} }

Implementation of cache caching mechanism used in Java

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.