[关闭]
@867976167 2020-03-24T11:46:56.000000Z 字数 1001 阅读 937

缓存算法简介————LRU算法

LRU 算法


缓存算法简介

缓存是存储用户经常需要的数据,减少读取数据的时间。一个缓存应当存储尽可能多的有用的数据,但是当缓存数据满了的时候,我们需要将一些可能没有用的数据淘汰出去,这就涉及到了常见的缓存淘汰算法;

LRU算法

这里简单介绍一下LRU算法,LRU是Least Recently Used 最近最少使用算法。算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”。

LRU算法最常见的实现是通过一个链表来实现:

!

  1. 新数据插入到链表头部;
  2. 每当缓存命中(即缓存数据被访问),则将数据移到链表头部;
  3. 当链表满的时候,将链表尾部的数据丢弃。
    下面是LeetCode上关于LRU的题的解法
  1. public class LRUCache {
  2. //使用linkedHashMap可以保证顺序
  3. LinkedHashMap<Integer, Integer> map = null;
  4. int count;
  5. public LRUCache(int capacity) {
  6. this.count = capacity;
  7. // 重写 LinkedHashMap方法,true代表排序模式
  8. map = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true) {
  9. // 在调用put方法时调用此方法,若返回true,则移除最旧的条目
  10. protected boolean removeEldestEntry(
  11. Map.Entry<Integer, Integer> eldest) {
  12. return map.size() > count;
  13. }
  14. };
  15. }
  16. public int get(int key) {
  17. if (map.containsKey(key)) {
  18. return map.get(key);
  19. } else {
  20. return -1;
  21. }
  22. }
  23. public void set(int key, int value) {
  24. map.put(key, value);
  25. }
  26. }

本文参考:http://blog.csdn.net/yunhua_lee/article/details/7599671

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注