java中实现LRU算法

来源:互联网 发布:魔兽争霸数据修改器 编辑:程序博客网 时间:2024/06/06 01:29

1.所谓的LRU(Least Recently Used算法,就是最近最少使用原则;为什么要有这个原则,目前就是可以提高系统的性能和吞吐量,在使用缓存的时候,可以使用此原则将最近最少使用的数据删除掉,不仅可以节省大量的内存空间,而且对系统的性能有很大的好处。

2.如果要了解LRU算法,首先不得不了解的就是LinkedHashMap

(1)他是HashMap的一个子类,虽然没有HashMap使用的场景多,但是关键时刻作用还是很多,因为LinkedHashMap他保存了插入的顺序,通过遍历获取数据的时候第一个得到的必然是第一个插入的数据,也可以通过构造函数:

public LinkedHashMap(int initialCapacity,float loadFactor,boolean accessOrder),其中的accessOrder如果为true,则按照访问顺序迭代,false按照插入顺序迭代。

(2)LinkedHashMap在遍历的时候会比HashMap慢,不过也有特殊的情况,在HashMap容量很大的时候,而数据很少, 此时遍历就比LinkedHashMap慢,因为HashMap遍历速度跟容量有关,而LinkedHashMap跟容量无关跟数据量有关系。

3.言归正传,继续说LRU算法,实现LRU算法必须重写LinkedHashMap的removeEldestEntry这个方法,下面是JDK中对此的注释:

/**     * Returns <tt>true</tt> if this map should remove its eldest entry.     * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after     * inserting a new entry into the map.  It provides the implementor     * with the opportunity to remove the eldest entry each time a new one     * is added.  This is useful if the map represents a cache: it allows     * the map to reduce memory consumption by deleting stale entries.     *     * <p>Sample use: this override will allow the map to grow up to 100     * entries and then delete the eldest entry each time a new entry is     * added, maintaining a steady state of 100 entries.     * <strong><pre>     *     private static final int MAX_ENTRIES = 100;     *     *     protected boolean removeEldestEntry(Map.Entry eldest) {     *        return size() > MAX_ENTRIES;     *     }     * </pre></strong>     *     * <p>This method typically does not modify the map in any way,     * instead allowing the map to modify itself as directed by its     * return value.  It <i>is</i> permitted for this method to modify     * the map directly, but if it does so, it <i>must</i> return     * <tt>false</tt> (indicating that the map should not attempt any     * further modification).  The effects of returning <tt>true</tt>     * after modifying the map from within this method are unspecified.     *     * <p>This implementation merely returns <tt>false</tt> (so that this     * map acts like a normal map - the eldest element is never removed).     *     * @param    eldest The least recently inserted entry in the map, or if     *           this is an access-ordered map, the least recently accessed     *           entry.  This is the entry that will be removed it this     *           method returns <tt>true</tt>.  If the map was empty prior     *           to the <tt>put</tt> or <tt>putAll</tt> invocation resulting     *           in this invocation, this will be the entry that was just     *           inserted; in other words, if the map contains a single     *           entry, the eldest entry is also the newest.     * @return   <tt>true</tt> if the eldest entry should be removed     *           from the map; <tt>false</tt> if it should be retained.     */    protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {        return false;    }

说的非常清楚,还有实例,下面是一个实现的样例供参考:

public class LRUTest {    /**   * 加载因子   */  private static final float loadFactor = 0.8f;    private LinkedHashMap<String, Object> map;    /**   * 初始化大小,即缓存中只保留此大小的数据量,超过了就会用到LRU原则了   */  private int cacheSize;    public LRUTest(int cacheSize){    this.cacheSize = cacheSize;    //如果为true,则按照访问顺序遍历    map = new LinkedHashMap<String,Object>(cacheSize, loadFactor, true){      private static final long serialVersionUID = 1;            @Override      protected boolean removeEldestEntry(Map.Entry<String,Object> eldest) {        return size() > LRUTest.this.cacheSize;      }    };  }    public synchronized Object get(String key) {    return map.get(key);  }    public synchronized void put(String key, Object value) {    map.put(key, value);  }    public synchronized int usedEntries() {    return map.size();  }    public synchronized Collection<Map.Entry<String, Object>> getAll() {    return new ArrayList<Map.Entry<String, Object>>(map.entrySet());  }}


0 0
原创粉丝点击