通过LinkedHashMap实现LRU算法

一、基于LinkedHashMap源码分析

方法调用流程(这里只是以put方法位例)

put() -> putVal() -> afterNodeInsertion() -> removeEldestEntry()

//向Map中添加元素
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
}

 

//真实添加元素
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        ......
		//判断是否扩容
        if (++size > threshold)
            resize();
		//主要方法
        afterNodeInsertion(evict);
        return null;
}

  

//节点插入
void afterNodeInsertion(boolean evict) { // possibly remove eldest
        LinkedHashMap.Entry<K,V> first;
        if (evict && (first = head) != null && removeEldestEntry(first)) {
            K key = first.key;
            removeNode(hash(key), key, null, false, true);
        }
}

  

//移除最大节点策略,LinkedHashMap是不剔除最大节点的,
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
        return false;
}

二、自己实现LRU算法

   /**
     * Constructs an empty <tt>LinkedHashMap</tt> instance with the
     * specified initial capacity, load factor and ordering mode.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @param  accessOrder     the ordering mode - <tt>true</tt> for
     *         access-order, <tt>false</tt> for insertion-order
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
public LinkedHashMap(int initialCapacity,
                         float loadFactor,
                         boolean accessOrder) {
        super(initialCapacity, loadFactor);
        this.accessOrder = accessOrder;
 }


Map<Integer,Object> map = Collections.synchronizedMap(
//16是map容器的大小,.75F是负载因子,true代表按招访问顺序进行排序
new LinkedHashMap<Integer, Object>(16,.75F,true){
    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, Object> eldest) 
    {
      return size() > 16;
    }
 });

  

posted @ 2020-08-31 09:51  码农的进击  阅读(192)  评论(0编辑  收藏  举报