LRU算法的小型缓存

package niewei.test4;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Collection;
import java.util.Map;
import java.util.Random;
import java.util.ArrayList;

/*假设有一个list容量只有10,而你的数据库的数据有100个,访问是随机的,
请基于访问次数,做一个LRU算法的小型缓存。注意线程安全!*/

public class LRUCache<K, V> {

    private static final float hashTableLoadFactor = 0.75f;

    private LinkedHashMap<K, V> map;
    private int cacheSize;

    public LRUCache(int cacheSize) {
        this.cacheSize = cacheSize;
        int hashTableCapacity = (int) Math.ceil(cacheSize / hashTableLoadFactor) + 1;
        map = new LinkedHashMap<K, V>(hashTableCapacity, hashTableLoadFactor, true) {
            private static final long serialVersionUID = 1;

            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                return size() > LRUCache.this.cacheSize;
            }
        };
    }

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

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

    public synchronized void clear() {
        map.clear();
    }

    public synchronized int usedEntries() {
        return map.size();
    }

    public synchronized Collection<Map.Entry<K, V>> getAll() {
        return new ArrayList<Map.Entry<K, V>>(map.entrySet());
    }

    public static void main(String[] args) {
        List<String> list1 = new ArrayList<>();
        Random r = new Random();
        // 给list1设置100个
        for (int i = 0; i < 100; i++) {
            list1.add("" + i + "");
        }
        LRUCache<String, String> list2 = new LRUCache<String, String>(10);
        for (int i = 0; i < 10; i++) {
            list2.put("" + i + "", list1.get(r.nextInt(100)));
        }
        System.out.println("添加10个,结果0-9");
        for (Map.Entry<String, String> e : list2.getAll())
            System.out.print(e.getKey() + ":" + e.getValue() + " ,");
        list2.put("10", list1.get(r.nextInt(100)));
        System.out.println("\n添加11个,结果为1-10");
        for (Map.Entry<String, String> e : list2.getAll())
            System.out.print(e.getKey() + ":" + e.getValue() + " ,");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值