利用LinkedHashMap实现LRU缓存策略

利用LinkedHashMap实现移除最近最少使用的缓存策略,只需要重载removeEldestEntry(Entry<Object, Object> eldest)方法即可。 

 

public class LruCache implements Cache {
    
    private final Map<Object, Object> store;

    public LruCache(URL url) {
        final int max = url.getParameter("cache.size", 1000);
        this.store = new LinkedHashMap<Object, Object>() {
            private static final long serialVersionUID = -3834209229668463829L;
            @Override
            protected boolean removeEldestEntry(Entry<Object, Object> eldest) {
                return size() > max;
            }
        };
    }

    public void put(Object key, Object value) {
        synchronized (store) {
            store.put(key, value);
        }
    }

    public Object get(Object key) {
        synchronized (store) {
            return store.get(key);
        }
    }

}
 参考: http://dennis-zane.iteye.com/blog/128278

你可能感兴趣的:(LruCache)