A Java Virtual cache tool that mimics memcached to cache Java objects
1 ImportJava.io.ByteArrayInputStream;2 ImportJava.io.ByteArrayOutputStream;3 ImportJava.io.ObjectInputStream;4 ImportJava.io.ObjectOutputStream;5 ImportJava.util.concurrent.ConcurrentHashMap;6 ImportJava.util.Map;7 8 /**9 * Java MAP Cache Manager improved versionTen * Features: Wireless range, check out when the expiration, serialization to achieve the depth of cloning, coverage principle One * Problem: Thread safety, aging loss caused by cloning A * @authorFrank - * - */ the Public classvirtualcache{ - - /** - * Development Mode + */ - Private BooleanIsdev =false; + A Private StaticString Error_set = "Virtualcache Cache data Exception: key="; at - Private StaticString error_get= "Virtualcache out Data exception: key="; - - /** - * Virtual Cache - */ in PrivateMap<string,object> cache =NewConcurrenthashmap<string, object>(); - to /** + * Expiry Time - */ the Privatemap<string,long> tasks =NewConcurrenthashmap<string,long>(); * $ PublicVirtualcache (BooleanIsdev) {Panax Notoginseng This. Isdev =Isdev; - } the + PublicVirtualcache () { A the } + - /** $ * Deep Cloning $ */ - PrivateObject Clone (String key,object obj,BooleanIsSet) { - if(obj = =NULL) the return NULL; -Bytearrayoutputstream bo =NULL;WuyiObjectOutputStream oo =NULL; theBytearrayinputstream bi =NULL; -ObjectInputStream Oi =NULL; WuObject value =NULL; - Try { Aboutbo=NewBytearrayoutputstream (); $OO =NewObjectOutputStream (bo); - oo.writeobject (obj); -Bi=NewBytearrayinputstream (Bo.tobytearray ()); -Oi=NewObjectInputStream (BI); AValue =Oi.readobject (); +}Catch(Exception e) { the This. Printerror (E, key,isset); -}finally{ $ if(Oo! =NULL) the Try { the oo.close (); the}Catch(Exception e) { the This. Printerror (E, key,isset); - } in if(Oi! =NULL) the Try { the oi.close (); About}Catch(Exception e) { the This. Printerror (E, key,isset); the } the } + returnvalue; - } the Bayi /** the * Log Output the */ - Private voidPrinterror (Exception e,string Key,BooleanIsSet) { - if(IsSet) theSystem.err.println (Error_set +key); the Else theSystem.err.println (Error_get +key); the if( This. Isdev) - e.printstacktrace (); the } the the /**94 * Cache the */ the Public voidSet (String key,object value,LongTimeout) { the This. Delete (key);98 This. Cache.put (Key, This. Clone (Key,value,true)); About if(Timeout > 0l) - This. Tasks.put (key,timeout*1000l +System.currenttimemillis ());101 }102 103 /**104 * Get Cache the */106 PublicObject get (String key) {107Long Timeout = This. Tasks.get (key);108 if(Timeout! =NULL&& Timeout <=System.currenttimemillis ())109 This. Delete (key); the return This. Clone (Key, This. Cache.get (Key),false);111 } the 113 /** the * Delete Cache the */ the Public voidDelete (String key) {117 This. Cache.remove (key);118 This. Tasks.remove (key);119 } - 121}
Java map Implementation of the cache manager