JAVA的简单缓存机制_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > JAVA的简单缓存机制

JAVA的简单缓存机制

 2013/10/30 18:13:02  submaze  程序员俱乐部  我要评论(0)
  • 摘要:packagecache;importjava.util.Date;importjava.util.HashMap;importjava.util.HashSet;importjava.util.Iterator;importjava.util.Map;importjava.util.Set;publicclassCacheMgr{privatestaticMapcacheMap=newHashMap();privatestaticMapcacheConfMap=newHashMap()
  • 标签:Java 缓存
class="java" name="code">
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){
			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;
	
	
	public long getBeginTime() {
		return beginTime;
	}
	public void setBeginTime(long beginTime) {
		this.beginTime = beginTime;
	}
	public boolean isForever() {
		return isForever;
	}
	public void setForever(boolean isForever) {
		this.isForever = isForever;
	}
	public int getDurableTime() {
		return durableTime;
	}
	public void setDurableTime(int durableTime) {
		this.durableTime = durableTime;
	}
	
}
上一篇: 三张图片详解Asp.Net 全生命周期 下一篇: 没有下一篇了!
发表评论
用户名: 匿名