ibatis-LruCache
核心对象
当Map存储key数量超出初始化设置的size时,标记最老的key,下次put时会自行删除eldest key。
Map<Object, Object> keyMap = new LinkedHashMap();
为什么使用LinkedHashMap?支持头、尾,快速获取头结点,从Map中快速删除数据。
实现removeEldestEntry方法,用于获取eldestKey。
putObject时,执行cycleKeyList方法,用于从map中删除eldestKey。
LinkedHashMap 带有头(transient eldest)、尾指针(transient youngest),数据存储到HashMap中。
源码如下:
public class LruCache implements Cache { private final Cache delegate; private Map<Object, Object> keyMap; private Object eldestKey; public LruCache(Cache delegate) { this.delegate = delegate; setSize(1024); }public void setSize(final int size) { keyMap = new LinkedHashMap<Object, Object>(size, .75F, true) { private static final long serialVersionUID = 4267176411845948333L; @Override protected boolean removeEldestEntry(Map.Entry<Object, Object> eldest) { boolean tooBig = size() > size; if (tooBig) { eldestKey = eldest.getKey(); } return tooBig; } }; } @Override public void putObject(Object key, Object value) { delegate.putObject(key, value); cycleKeyList(key); }private void cycleKeyList(Object key) { keyMap.put(key, key); if (eldestKey != null) { delegate.removeObject(eldestKey); eldestKey = null; } } }
收藏文章数量从多到少与“把书读薄”是一个道理