引子:
我們平時總會有一個電話本記錄所有朋友的電話,但是,如果有朋友經常聯繫,那些朋友的電話號碼不用翻電話本我們也能記住,但是,如果長時間沒有聯繫了,要再次聯繫那位朋友的時候,我們又不得不求助電話本,但是,通過電話本查找還是很費時間的。但是,我們大腦能夠記住的東西是一定的,我們只能記住自己最熟悉的,而長時間不熟悉的自然就忘記了。
其實,計算機也用到了同樣的一個概念,我們用緩存來存放以前讀取的數據,而不是直接丟掉,這樣,再次讀取的時候,可以直接在緩存裏面取,而不用再重新查找一遍,這樣系統的反應能力會有很大提高。但是,當我們讀取的個數特別大的時候,我們不可能把所有已經讀取的數據都放在緩存裏,畢竟內存大小是一定的,我們一般把最近常讀取的放在緩存裏(相當於我們把最近聯繫的朋友的姓名和電話放在大腦裏一樣)。現在,我們就來研究這樣一種緩存機制。
LRU緩存:
LRU緩存利用了這樣的一種思想。LRU是Least Recently Used 的縮寫,翻譯過來就是“最近最少使用”,也就是說,LRU緩存把最近最少使用的數據移除,讓給最新讀取的數據。而往往最常讀取的,也是讀取次數最多的,所以,利用LRU緩存,我們能夠提高系統的performance.
實現:
要實現LRU緩存,我們首先要用到一個類 LinkedHashMap。 用這個類有兩大好處:一是它本身已經實現了按照訪問順序的存儲,也就是說,最近讀取的會放在最前面,最最不常讀取的會放在最後(當然,它也可以實現按照插入順序存儲)。第二,LinkedHashMap本身有一個方法用於判斷是否需要移除最不常讀取的數,但是,原始方法默認不需要移除(這是,LinkedHashMap相當於一個linkedlist),所以,我們需要override這樣一個方法,使得當緩存裏存放的數據個數超過規定個數後,就把最不常用的移除掉。LinkedHashMap的API寫得很清楚,推薦大家可以先讀一下。
要基於LinkedHashMap來實現LRU緩存,我們可以選擇inheritance, 也可以選擇 delegation, 我更喜歡delegation。基於delegation的實現已經有人寫出來了,而且寫得很漂亮,我就不班門弄斧了。代碼如下:
- import java.util.LinkedHashMap;
- import java.util.Collection;
- import java.util.Map;
- import java.util.ArrayList;
- /**
- * An LRU cache, based on <code>LinkedHashMap</code>.
- *
- * <p>
- * This cache has a fixed maximum number of elements (<code>cacheSize</code>).
- * If the cache is full and another entry is added, the LRU (least recently used) entry is dropped.
- *
- * <p>
- * This class is thread-safe. All methods of this class are synchronized.
- *
- * <p>
- * Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
- * Multi-licensed: EPL / LGPL / GPL / AL / BSD.
- */
- public class LRUCache<K,V> {
- private static final float hashTableLoadFactor = 0.75f;
- private LinkedHashMap<K,V> map;
- private int cacheSize;
- /**
- * Creates a new LRU cache.
- * @param cacheSize the maximum number of entries that will be kept in this cache.
- */
- public LRUCache (int cacheSize) {
- this.cacheSize = cacheSize;
- int hashTableCapacity = (int)Math.ceil(cacheSize / hashTableLoadFactor) + 1;
- map = new LinkedHashMap<K,V>(hashTableCapacity, hashTableLoadFactor, true) {
- // (an anonymous inner class)
- private static final long serialVersionUID = 1;
- @Override protected boolean removeEldestEntry (Map.Entry<K,V> eldest) {
- return size() > LRUCache.this.cacheSize; }}; }
- /**
- * Retrieves an entry from the cache.<br>
- * The retrieved entry becomes the MRU (most recently used) entry.
- * @param key the key whose associated value is to be returned.
- * @return the value associated to this key, or null if no value with this key exists in the cache.
- */
- public synchronized V get (K key) {
- return map.get(key); }
- /**
- * Adds an entry to this cache.
- * The new entry becomes the MRU (most recently used) entry.
- * If an entry with the specified key already exists in the cache, it is replaced by the new entry.
- * If the cache is full, the LRU (least recently used) entry is removed from the cache.
- * @param key the key with which the specified value is to be associated.
- * @param value a value to be associated with the specified key.
- */
- public synchronized void put (K key, V value) {
- map.put (key, value); }
- /**
- * Clears the cache.
- */
- public synchronized void clear() {
- map.clear(); }
- /**
- * Returns the number of used entries in the cache.
- * @return the number of entries currently in the cache.
- */
- public synchronized int usedEntries() {
- return map.size(); }
- /**
- * Returns a <code>Collection</code> that contains a copy of all cache entries.
- * @return a <code>Collection</code> with a copy of the cache content.
- */
- public synchronized Collection<Map.Entry<K,V>> getAll() {
- return new ArrayList<Map.Entry<K,V>>(map.entrySet()); }
- } // end class LRUCache
- ------------------------------------------------------------------------------------------
- // Test routine for the LRUCache class.
- public static void main (String[] args) {
- LRUCache<String,String> c = new LRUCache<String, String>(3);
- c.put ("1", "one"); // 1
- c.put ("2", "two"); // 2 1
- c.put ("3", "three"); // 3 2 1
- c.put ("4", "four"); // 4 3 2
- if (c.get("2") == null) throw new Error(); // 2 4 3
- c.put ("5", "five"); // 5 2 4
- c.put ("4", "second four"); // 4 5 2
- // Verify cache content.
- if (c.usedEntries() != 3) throw new Error();
- if (!c.get("4").equals("second four")) throw new Error();
- if (!c.get("5").equals("five")) throw new Error();
- if (!c.get("2").equals("two")) throw new Error();
- // List cache content.
- for (Map.Entry<String, String> e : c.getAll())
- System.out.println (e.getKey() + " : " + e.getValue()); }
代碼出自:http://www.source-code.biz/snippets/java/6.htm
在博客 http://gogole.iteye.com/blog/692103 裏,作者使用的是雙鏈表 + hashtable 的方式實現的。如果在面試題裏考到如何實現LRU,考官一般會要求使用雙鏈表 + hashtable 的方式。 所以,我把原文的部分內容摘抄如下:
雙鏈表 + hashtable實現原理:
將Cache的所有位置都用雙連表連接起來,當一個位置被命中之後,就將通過調整鏈表的指向,將該位置調整到鏈表頭的位置,新加入的Cache直接加到鏈表頭中。這樣,在多次進行Cache操作後,最近被命中的,就會被向鏈表頭方向移動,而沒有命中的,而想鏈表後面移動,鏈表尾則表示最近最少使用的Cache。當需要替換內容時候,鏈表的最後位置就是最少被命中的位置,我們只需要淘汰鏈表最後的部分即可。
- public class LRUCache {
- private int cacheSize;
- private Hashtable<Object, Entry> nodes;//緩存容器
- private int currentSize;
- private Entry first;//鏈表頭
- private Entry last;//鏈表尾
- public LRUCache(int i) {
- currentSize = 0;
- cacheSize = i;
- nodes = new Hashtable<Object, Entry>(i);//緩存容器
- }
- /**
- * 獲取緩存中對象,並把它放在最前面
- */
- public Entry get(Object key) {
- Entry node = nodes.get(key);
- if (node != null) {
- moveToHead(node);
- return node;
- } else {
- return null;
- }
- }
- /**
- * 添加 entry到hashtable, 並把entry
- */
- public void put(Object key, Object value) {
- //先查看hashtable是否存在該entry, 如果存在,則只更新其value
- Entry node = nodes.get(key);
- if (node == null) {
- //緩存容器是否已經超過大小.
- if (currentSize >= cacheSize) {
- nodes.remove(last.key);
- removeLast();
- } else {
- currentSize++;
- }
- node = new Entry();
- }
- node.value = value;
- //將最新使用的節點放到鏈表頭,表示最新使用的.
- moveToHead(node);
- nodes.put(key, node);
- }
- /**
- * 將entry刪除, 注意:刪除操作只有在cache滿了纔會被執行
- */
- public void remove(Object key) {
- Entry node = nodes.get(key);
- //在鏈表中刪除
- if (node != null) {
- if (node.prev != null) {
- node.prev.next = node.next;
- }
- if (node.next != null) {
- node.next.prev = node.prev;
- }
- if (last == node)
- last = node.prev;
- if (first == node)
- first = node.next;
- }
- //在hashtable中刪除
- nodes.remove(key);
- }
- /**
- * 刪除鏈表尾部節點,即使用最後 使用的entry
- */
- private void removeLast() {
- //鏈表尾不爲空,則將鏈表尾指向null. 刪除連表尾(刪除最少使用的緩存對象)
- if (last != null) {
- if (last.prev != null)
- last.prev.next = null;
- else
- first = null;
- last = last.prev;
- }
- }
- /**
- * 移動到鏈表頭,表示這個節點是最新使用過的
- */
- private void moveToHead(Entry node) {
- if (node == first)
- return;
- if (node.prev != null)
- node.prev.next = node.next;
- if (node.next != null)
- node.next.prev = node.prev;
- if (last == node)
- last = node.prev;
- if (first != null) {
- node.next = first;
- first.prev = node;
- }
- first = node;
- node.prev = null;
- if (last == null)
- last = first;
- }
- /*
- * 清空緩存
- */
- public void clear() {
- first = null;
- last = null;
- currentSize = 0;
- }
- }
- class Entry {
- Entry prev;//前一節點
- Entry next;//後一節點
- Object value;//值
- Object key;//鍵
- }