简单的Map缓存机制实现

简单的Map缓存机制实现

大致思路是用一个单例的Map实现,当然此Map得是线程安全的--ConcurrentHashMap

原本项目需求是缓存十条消息,所以打算用Map实现缓存机制。中途夭折下面具体尚未实现。。。

当然此代码仞为半成品,具体得根据项目需求采用不同的原则清除缓存

package per.zww.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CachePool {
    private static CachePool cachePool;
    private Map<Object, Object> cacheItems;
    private CachePool() {
        cacheItems =new ConcurrentHashMap<Object, Object>();
    }
    /**
     * 获取唯一实例
     * @return instance
     */
    public static CachePool getInstance() {
        if (cachePool ==null) {
            synchronized (CachePool.class) {
                if (cachePool ==null) {
                    cachePool =new CachePool();
                }
            }
        }
        return cachePool;
    }
    
    /**
     * 获取所有cache信息
     * @return cacheItems
     */
    public Map<Object, Object> getCacheItems() {
        return this.cacheItems;
    }
    
    /**
     * 清空cache
     */
    public void clearAllItems() {
        cacheItems.clear();
    }
    
    /**
     * 获取指定cache信息
     * @return cacheItem
     */
    public Object getCacheItem(Object key) {
        if (cacheItems.containsKey(key)) {
            return cacheItems.get(key);
        }
        return null;
    }
    
    /**
     * 存放cache信息
     */
    public void putCacheItem(Object key,Object value) {
        if (!cacheItems.containsKey(key)) {
            cacheItems.put(key, value);
        }
    }
    
    /**
     * 删除一个cache
     */
    public void removeCacheItem(Object key) {
        if (cacheItems.containsKey(key)) {
            cacheItems.remove(key);
        }
    }
    
    /**
     * 获取cache长度
     * @return size
     */
    public int getSize() {
        return cacheItems.size();
    }
    
}

 

posted @ 2016-01-11 23:33  胖胖的半山兄  阅读(5587)  评论(0编辑  收藏  举报