最近在逛博客的時候看到了有關Redis方面的面試題,其中提到了Redis在內存達到最大限制的時候會使用LRU等淘汰機制,而後找了這方面的一些資料與你們分享一下。java
LRU整體大概是這樣的,最近使用的放在前面,最近沒用的放在後面,若是來了一個新的數,此時內存滿了,就須要把舊的數淘汰,那爲了方便移動數據,確定就得使用鏈表相似的數據結構,再加上要判斷這條數據是否是最新的或者最舊的那麼應該也要使用hashmap等key-value形式的數據結構。node
public class LRUCache { int capacity; Map<Integer,Integer> map; public LRUCache(int capacity){ this.capacity = capacity; map = new LinkedHashMap<>(); } public int get(int key){ //若是沒有找到 if (!map.containsKey(key)){ return -1; } //找到了就刷新數據 Integer value = map.remove(key); map.put(key,value); return value; } public void put(int key,int value){ if (map.containsKey(key)){ map.remove(key); map.put(key,value); return; } map.put(key,value); //超出capacity,刪除最久沒用的即第一個,或者能夠複寫removeEldestEntry方法 if (map.size() > capacity){ map.remove(map.entrySet().iterator().next().getKey()); } } public static void main(String[] args) { LRUCache lruCache = new LRUCache(10); for (int i = 0; i < 10; i++) { lruCache.map.put(i,i); System.out.println(lruCache.map.size()); } System.out.println(lruCache.map); lruCache.put(10,200); System.out.println(lruCache.map); }
public class LRUCache { private int capacity; private Map<Integer,ListNode>map; private ListNode head; private ListNode tail; public LRUCache2(int capacity){ this.capacity = capacity; map = new HashMap<>(); head = new ListNode(-1,-1); tail = new ListNode(-1,-1); head.next = tail; tail.pre = head; } public int get(int key){ if (!map.containsKey(key)){ return -1; } ListNode node = map.get(key); node.pre.next = node.next; node.next.pre = node.pre; return node.val; } public void put(int key,int value){ if (get(key)!=-1){ map.get(key).val = value; return; } ListNode node = new ListNode(key,value); map.put(key,node); moveToTail(node); if (map.size() > capacity){ map.remove(head.next.key); head.next = head.next.next; head.next.pre = head; } } //把節點移動到尾巴 private void moveToTail(ListNode node) { node.pre = tail.pre; tail.pre = node; node.pre.next = node; node.next = tail; } //定義雙向鏈表節點 private class ListNode{ int key; int val; ListNode pre; ListNode next; //初始化雙向鏈表 public ListNode(int key,int val){ this.key = key; this.val = val; pre = null; next = null; } } }
像第一種方式,若是複寫removeEldestEntry會更簡單,這裏簡單的展現一下面試
public class LRUCache extends LinkedHashMap<Integer,Integer> { private int capacity; @Override protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) { return size() > capacity; } }
原文連接:https://blog.csdn.net/Grady00...spring
版權聲明:本文爲CSDN博主「拉霍拉卡」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連接及本聲明。數據結構
近期熱文推薦:intellij-idea
1.600+ 道 Java面試題及答案整理(2021最新版)ide
2.終於靠開源項目弄到 IntelliJ IDEA 激活碼了,真香!工具
3.阿里 Mock 工具正式開源,幹掉市面上全部 Mock 工具!this
4.Spring Cloud 2020.0.0 正式發佈,全新顛覆性版本!idea
以爲不錯,別忘了隨手點贊+轉發哦!