簡單的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(); } }