學過操做系統的人都知道LRU頁面切換算法,其實這個算法不單單只是能在頁面切換中應用到,在緩存中也有很實際的應用。最典型的實現方式是採用LinkedHashMap來實現這個緩存,你們能夠在Java源碼裏面看到這個類的做者關於這個的描述,不過全是英文,可是卻明確提到過。html
下面廢話很少說,直接展現我本身關於這個算法實現的代碼吧,親測經過:java
核心算法代碼:算法
package hk.inso.www.cache; import java.util.Hashtable; import java.util.LinkedList; /** * Created by IntelliJ IDEA. * Date: 8/7/15 4:46 PM * Author: Richard */ public class LinkedListCache<Object>{ //默認的緩存大小 private static int CAPACITY = 0; //引用一個雙向連接表 private LinkedList<Object> list; //構造函數 public LinkedListCache(int capacity) { this.CAPACITY = capacity; list = new LinkedList<Object>(); } //添加一個元素 public synchronized void put(Object object) { if(list != null && list.contains(object)) { list.remove(object); } removeLeastVisitElement(); list.addFirst(object); } //移除最近訪問次數最少的元素 private synchronized void removeLeastVisitElement() { int size = size(); //注意,這兒必須得是CAPACITY - 1不然所獲的size比原來大1 if(size > (CAPACITY - 1) ) { Object object = list.removeLast(); System.out.println("本次被踢掉的元素是:" + object.toString()); } } //獲取第N個索引下面的元素 public synchronized Object get(int index) { return list.get(index); } //清空緩存 public synchronized void clear() { list.clear(); } //獲取連接表的大小 public int size() { if(list == null) { return 0; } return list.size(); } //toString方法 public String toString() { return list.toString(); } }
測試代碼:緩存
package hk.inso.www.test; import hk.inso.www.cache.LRUCache; import hk.inso.www.cache.LinkedListCache; import hk.inso.www.cache.MapCache; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * Created by Richard on 8/5/15. */ public class CacheTest { public static void main(String[] args) throws InterruptedException { LinkedListCache linkedListCache = new LinkedListCache<String>(5); linkedListCache.put("1"); System.out.println(linkedListCache.toString()); Thread.sleep(1000); linkedListCache.put("2"); System.out.println(linkedListCache.toString()); Thread.sleep(1000); linkedListCache.put("3"); System.out.println(linkedListCache.toString()); Thread.sleep(1000); linkedListCache.put("4"); System.out.println(linkedListCache.toString()); Thread.sleep(1000); linkedListCache.put("5"); System.out.println(linkedListCache.toString()); Thread.sleep(1000); linkedListCache.put("1"); System.out.println(linkedListCache.toString()); Thread.sleep(1000); linkedListCache.put("6"); System.out.println(linkedListCache.toString()); Thread.sleep(1000); linkedListCache.put("4"); System.out.println(linkedListCache.toString()); Thread.sleep(1000); linkedListCache.put("7"); System.out.println(linkedListCache.toString()); } }
不要吐槽這個哈,時間關係,就直接這麼演示了,你能夠直接拷貝下來運行就能夠了。但願能夠幫到你!函數