Java 缓存池(使用Map实现)

之前只是听说过缓存池,也没有具体的接触到,今天做项目忽然想到了用缓存池,就花了一上午的时间研究了下缓存池的原理,并实现了基本的缓存池功能。

/**
 * 缓存池
 * @author xiaoquan
 * @create 2015年3月13日 上午10:32:13
 * @see
 */
public class CachePool {
    private static CachePool instance;//缓存池唯一实例
    private static Map<String,Object> cacheItems;//缓存Map
    
    private CachePool(){
        cacheItems = new HashMap<String,Object>();
    }
    /**
     * 得到唯一实例
     * @return
     */
    public synchronized static CachePool getInstance(){
        if(instance == null){
            instance = new CachePool();
        }
        return instance;
    }
    /**
     * 清除所有Item缓存
     */
    public synchronized void clearAllItems(){
        cacheItems.clear();
    }
    /**
     * 获取缓存实体
     * @param name
     * @return
     */
    public synchronized Object getCacheItem(String name){
        if(!cacheItems.containsKey(name)){
            return null;
        }
        CacheItem cacheItem = (CacheItem) cacheItems.get(name);
        if(cacheItem.isExpired()){
            return null;
        }
        return cacheItem.getEntity();
    }
    /**
     * 存放缓存信息
     * @param name
     * @param obj
     * @param expires
     */
    public synchronized void putCacheItem(String name,Object obj,long expires){
        if(!cacheItems.containsKey(name)){
            cacheItems.put(name, new CacheItem(obj, expires));
        }
        CacheItem cacheItem = (CacheItem) cacheItems.get(name);
        cacheItem.setCreateTime(new Date());
        cacheItem.setEntity(obj);
        cacheItem.setExpireTime(expires);
    }
    public synchronized void putCacheItem(String name,Object obj){
        putCacheItem(name,obj,-1);
    }
    
    /**
     * 移除缓存数据
     * @param name
     */
    public synchronized void removeCacheItem(String name){
        if(!cacheItems.containsKey(name)){
            return;
        }
        cacheItems.remove(name);
    }
    
    /**
     * 获取缓存数据的数量
     * @return
     */
    public int getSize(){
        return cacheItems.size();
    }
}

 

public class CacheItem {
	private Date createTime = new Date();//创建缓存的时间
	private long expireTime = 1;//缓存期满的时间
	private Object entity;//缓存的实体
	
	public CacheItem(Object obj,long expires){
		this.entity = obj;
		this.expireTime = expires;
	}
	
	public boolean isExpired(){
		return (expireTime != -1 && new Date().getTime()-createTime.getTime() > expireTime);
	}
        /**
         * 省略getter、setter方法 
         */ 
}

 

posted @ 2015-03-13 15:35  xiao_quan  阅读(4843)  评论(0编辑  收藏  举报