设计一套具备LRU过期策略的缓存程序

2017-06-22  本文已影响0人  zychen143

考察点:

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

/**
 * Created by zhangyuanchen on 2017/6/22.
 */
public class LruTest<K, V> {

    private int cacheSize;
    private LinkedHashMap<K, V> map;
    private static final float loadFactor = 0.75f;

    /**
     * @param cacheSize 缓存大小
     */
    public LruTest(int cacheSize) {
        this.cacheSize = cacheSize;
        int initialCapacity = (int) Math.ceil(cacheSize / loadFactor) + 1;
        map = new LinkedHashMap<K, V>(initialCapacity, loadFactor, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                return size() > LruTest.this.cacheSize;
            }
        };
    }

    public synchronized void put(K key, V value) {
        map.put(key, value);
    }

    public synchronized V get(K key) {
        return map.get(key);
    }

    public static void main(String[] args) {
        LruTest<Integer, String> lruTest = new LruTest<Integer, String>(3);
        lruTest.put(1, "one");  // 1
        lruTest.put(2, "two");  // 2,1
        lruTest.put(3, "three"); // 3,2,1
        lruTest.put(4, "four"); // 4,3,2
        lruTest.get(3); // 3,4,2
        lruTest.get(2); // 2,3,4
    }
}

上一篇 下一篇

猜你喜欢

热点阅读