浏览 5233 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2007-07-09
这是缓存器核心类。 package cc.vicp.eden.cache; import java.util.*; public class CachePool { private HashMap<Object, Object> pool; private LinkedList list; private int capacity; public CachePool(int size) { pool = new HashMap<Object, Object>(); list = new LinkedList<Object>(); this.capacity = size; } public synchronized Object get(Object key) { Object value = pool.get(key); if(value != null) { list.remove(key); list.addFirst(key); } return value; } public synchronized void put(Object key, Object value) { Object obj = null; if(pool.size() >= capacity) { obj = list.removeLast(); pool.remove(obj); } obj = pool.get(key); if(! value.equals(obj)) { pool.remove(key); } pool.put(key, value); list.remove(key); list.addFirst(key); } public synchronized Object remove(Object key) { Object value = pool.get(key); list.remove(key); return value; } public synchronized void clear() { pool.clear(); list.clear(); } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2007-07-09
这是提供了超时检测的缓存器类。
package cc.vicp.eden.cache; public class CacheManager extends CachePool { private static final int CAPACITY; static { CAPACITY = 10; } public CacheManager() { super(CacheManager.CAPACITY); } @Override public synchronized Object get(Object key) { Object value = super.get(key); if(value instanceof Expireable) { Expireable e = (Expireable) value; if(e.expire()) { remove(key); value = null; } } return value; } } interface Expireable { boolean expire(); } |
|
返回顶楼 | |
发表时间:2007-07-09
看了之后有点收获啊。以前去看了一下ehcache的文档,看不懂。看了楼主的“超简易”实现稍微懂了一点基本的思想。就是最长时间没有用的最有可能被移出。
|
|
返回顶楼 | |
发表时间:2007-07-09
你用apache的LRUMap不都解决了吗
|
|
返回顶楼 | |
发表时间:2007-07-09
其实继承HashMap来做Cache也很简单:)
import java.util.LinkedHashMap; import java.util.Map; /** * 一个实现LRU算法的Map * * @author Arbow */ public class LRUMap<K,V> extends LinkedHashMap<K,V> { private static final long serialVersionUID = -4653726313477788815L; private final int maxSize; /** * 构造一个指定容量的LRU Map * @param maxCapacity 最大容量 */ public LRUMap(int maxCapacity) { super(maxCapacity*4/3 + 1, 0.75f, true); this.maxSize = maxCapacity; } protected boolean removeEldestEntry(Map.Entry<K,V> entry) { return size() > maxSize; } } |
|
返回顶楼 | |