簡單的快取池實現
package com.cache;
import java.util.Date; import java.util.HashMap; import java.util.Map;
public class SampleCachePool {
private static SampleCachePool instance = null;
private Map pool;
private SampleCachePool() { pool = new HashMap(); }
public synchronized static SampleCachePool getInstance() { if (instance == null) { instance = new SampleCachePool(); } return instance; }
public synchronized void clearAllCacheContainer() { pool.clear(); }
public synchronized CacheContainer getCacheContainer(String name, boolean autoCreate) { if (pool.containsKey(name)) { return (CacheContainer) pool.get(name); } else if (autoCreate) {
CacheContainer container = new CacheContainer(); pool.put(name, container); return container;
} else { return null; } }
public synchronized CacheContainer getCacheContainer(String name) { return getCacheContainer(name, false); }
public class CacheContainer {
Map context = new HashMap();
public Object getContent(String name) { if (!context.containsKey(name)) { return null; } CacheItem item = (CacheItem) context.get(name); if (item.isExpired()) { return null; } else { return item.getEntity(); }
}
public void putContent(String name, Object obj, long expires) {
if (!context.containsKey(name)) { context.put(name, new CacheItem(obj, expires)); return; } CacheItem item = (CacheItem) context.get(name); item.setUpdateTime(new Date()); item.setExpireTimes(expires); item.setEntity(obj); }
public void putContent(String name, Object obj) { putContent(name, obj, -1); }
private class CacheItem { private Date createTime = new Date();
private Date updateTime = new Date();
private long expireTimes = -1;
private Object entity = null;
public CacheItem(Object obj, long expires) { entity = obj; expireTimes = expires; }
public boolean isExpired() { return (expireTimes != -1 && new Date().getTime() - updateTime.getTime() > expireTimes); }
public String toString() { return entity.toString(); }
public Date getCreateTime() { return createTime; }
public Object getEntity() { return entity; }
public Date getUpdateTime() { return updateTime; }
public void setCreateTime(Date date) { createTime = date; }
public void setEntity(Object object) { entity = object; }
public void setUpdateTime(Date date) { updateTime = date; }
public long getExpireTimes() { return expireTimes; }
public void setExpireTimes(long l) { expireTimes = l; }
}
}
}