All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.dexcoder.commons.cache.LRUCache Maven / Gradle / Ivy

There is a newer version: 2.3.5
Show newest version
package com.dexcoder.commons.cache;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * LRU缓存实现
 *
 * Created by liyd on 7/24/14.
 */
public class LRUCache extends AbstractCacheMap {

    /**
     * 构造方法
     * 
     * @param cacheSize
     * @param defaultExpire
     */
    public LRUCache(int cacheSize, long defaultExpire) {

        super(cacheSize, defaultExpire);

        //linkedHash已经实现LRU算法 是通过双向链表来实现,
        // 当某个位置被命中,通过调整链表的指向将该位置调整到头位置,
        // 新加入的内容直接放在链表头,如此一来,最近被命中的内容就向链表头移动,
        // 需要替换时,链表最后的位置就是最近最少使用的位置
        this.cacheMap = new LinkedHashMap>(cacheSize + 1, 1f, true) {

			private static final long serialVersionUID = 4789439462791125917L;

			@Override
            protected boolean removeEldestEntry(Map.Entry> eldest) {

                return LRUCache.this.removeEldestEntry(eldest);
            }

        };
    }

    /**
     * 插入元素时是否需要移除最老的元素(超过缓存大小时)
     * 
     * @param eldest
     * @return
     */
    private boolean removeEldestEntry(Map.Entry> eldest) {

        if (cacheSize == 0)
            return false;

        return size() > cacheSize;
    }

    /**
     * 只需要实现清除过期对象就可以了,linkedHashMap已经实现LRU
     */
    @Override
    protected int eliminateCache() {

        if (!isNeedClearExpiredObject()) {
            return 0;
        }

        Iterator> iterator = cacheMap.values().iterator();
        int count = 0;
        while (iterator.hasNext()) {
            CacheObject cacheObject = iterator.next();

            if (cacheObject.isExpired()) {
                iterator.remove();
                count++;
            }
        }

        return count;
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy