首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java简略的缓存

2012-08-31 
java简单的缓存import java.util.Dateimport java.util.HashMapimport java.util.HashSetimport java.u

java简单的缓存

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 synchronized static CacheMgr getInstance(){  if(cm==null){   cm = new CacheMgr();   Thread t = new ClearCache();   t.start();  }  return cm; } /**  * 增加缓存  * @param key  * @param value  * @param ccm 缓存对象  * @return   */ public  synchronized 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; } /**  * 删除缓存  * @param key  * @return   */ public  synchronized boolean removeCache(Object key){  cacheMap.remove(key);  cacheConfMap.remove(key);    System.out.println("now removeCache=="+cacheMap.size());    return true; } /**  * 删除所有缓存  */ public synchronized void removeAllCache(){ cacheMap.clear(); cacheConfMap.clear(); }  /**  * 在缓存中取值  * @param key  * @return  */ public synchronized Object getCacheContainer(Object key) {return getCacheContainer(key, false); } /**  * 在缓存中取值  * @param key   key值  * @param autoUpdate  在缓存中时间是否自动增加  * @return  */ public synchronized Object getCacheContainer(Object key,boolean autoUpdate) {if (cacheMap.containsKey(key)) {if(autoUpdate){CacheConfModel ccm = (CacheConfModel)cacheConfMap.get(key);ccm.setBeginTime((new Date()).getTime());cacheConfMap.put(key, ccm);}return cacheMap.get(key);}else {return null;}}  /**  * 清除缓存的类  * @author wanglj  * 继承Thread线程类  */ private 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();    }   }  } }}

热点排行