JAVA的简略缓存机制ITeye - 凯时娱乐

JAVA的简略缓存机制ITeye

2019年03月01日10时37分37秒 | 作者: 振荣 | 标签: 缓存,结构,安全 | 浏览: 864


阐明: 该缓存结构或许存在多线程安全问题,参阅ConcurrentHashMap线程安全结构,做修正

package cache;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class CacheMgr {
 private static Map cacheMap = new HashMap();
 private static Map cacheConfMap = new HashMap();
 private CacheMgr(){
 private static CacheMgr cm = null;
 //单例
 public static CacheMgr getInstance(){
 if (cm  null) {
 synchronized(CacheMgr.class){
 if(cm  null){
 cm = new CacheMgr();
 Thread t = new ClearCache();
 t.start();
 return cm;
 * 添加缓存
 public boolean addCache(Object key,Object value,CacheConfModel ccm){
 boolean flag = false;
 cacheMap.put(key, value);
 cacheConfMap.put(key, ccm);
 System.out.println("now addcache"+cacheMap.size());
 return true;
 public boolean removeCache(Object key){
 cacheMap.remove(key);
 cacheConfMap.remove(key);
 System.out.println("now removeCache"+cacheMap.size());
 return true;
 public static class ClearCache extends Thread{
 public void run(){
 while(true){
 Set tempSet = new HashSet();
 Set set = cacheConfMap.keySet();
 Iterator it = set.iterator();
 while(it.hasNext()){
 Object key = it.next();
 CacheConfModel ccm = (CacheConfModel)cacheConfMap.get(key);
 if(!ccm.isForever()){
 if((new Date().getTime()-ccm.getBeginTime()) = ccm.getDurableTime()*60*1000){ 
 //能够铲除,先记录下来 
 tempSet.add(key);
 //真实铲除
 Iterator tempIt = tempSet.iterator();
 while(tempIt.hasNext()){ 
 Object key = tempIt.next(); 
 cacheMap.remove(key); 
 cacheConfMap.remove(key); 
 System.out.println("now thread "+cacheMap.size());
 //歇息
 try {
 Thread.sleep(60*1000L);
 } catch (InterruptedException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
class CacheConfModel implements java.io.Serializable{
 private long beginTime;
 private boolean isForever = false;
 private int durableTime;                          
			
版权声明
本文来源于网络,版权归原作者所有,其内容与观点不代表凯时娱乐立场。转载文章仅为传播更有价值的信息,如采编人员采编有误或者版权原因,请与我们联系,我们核实后立即修改或删除。

猜您喜欢的文章