詳解Java實(shí)現(xiàn)LRU緩存
LRU是Least Recently Used 的縮寫(xiě),翻譯過(guò)來(lái)就是“最近最少使用”,LRU緩存就是使用這種原理實(shí)現(xiàn),簡(jiǎn)單的說(shuō)就是緩存一定量的數(shù)據(jù),當(dāng)超過(guò)設(shè)定的閾值時(shí)就把一些過(guò)期的數(shù)據(jù)刪除掉,比如我們緩存10000條數(shù)據(jù),當(dāng)數(shù)據(jù)小于10000時(shí)可以隨意添加,當(dāng)超過(guò)10000時(shí)就需要把新的數(shù)據(jù)添加進(jìn)來(lái),同時(shí)要把過(guò)期數(shù)據(jù)刪除,以確保我們最大緩存10000條,那怎么確定刪除哪條過(guò)期數(shù)據(jù)呢,采用LRU算法實(shí)現(xiàn)的話(huà)就是將最老的數(shù)據(jù)刪掉,廢話(huà)不多說(shuō),下面來(lái)說(shuō)下Java版的LRU緩存實(shí)現(xiàn)
Java里面實(shí)現(xiàn)LRU緩存通常有兩種選擇,一種是使用LinkedHashMap,一種是自己設(shè)計(jì)數(shù)據(jù)結(jié)構(gòu),使用鏈表+HashMap
LRU Cache的LinkedHashMap實(shí)現(xiàn)
LinkedHashMap自身已經(jīng)實(shí)現(xiàn)了順序存儲(chǔ),默認(rèn)情況下是按照元素的添加順序存儲(chǔ),也可以啟用按照訪問(wèn)順序存儲(chǔ),即最近讀取的數(shù)據(jù)放在最前面,最早讀取的數(shù)據(jù)放在最后面,然后它還有一個(gè)判斷是否刪除最老數(shù)據(jù)的方法,默認(rèn)是返回false,即不刪除數(shù)據(jù),我們使用LinkedHashMap實(shí)現(xiàn)LRU緩存的方法就是對(duì)LinkedHashMap實(shí)現(xiàn)簡(jiǎn)單的擴(kuò)展,擴(kuò)展方式有兩種,一種是inheritance,一種是delegation,具體使用什么方式看個(gè)人喜好
//LinkedHashMap的一個(gè)構(gòu)造函數(shù),當(dāng)參數(shù)accessOrder為true時(shí),即會(huì)按照訪問(wèn)順序排序,最近訪問(wèn)的放在最前,最早訪問(wèn)的放在后面 public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) { super(initialCapacity, loadFactor); this.accessOrder = accessOrder; } //LinkedHashMap自帶的判斷是否刪除最老的元素方法,默認(rèn)返回false,即不刪除老數(shù)據(jù) //我們要做的就是重寫(xiě)這個(gè)方法,當(dāng)滿(mǎn)足一定條件時(shí)刪除老數(shù)據(jù) protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return false; }
LRU緩存LinkedHashMap(inheritance)實(shí)現(xiàn)
采用inheritance方式實(shí)現(xiàn)比較簡(jiǎn)單,而且實(shí)現(xiàn)了Map接口,在多線(xiàn)程環(huán)境使用時(shí)可以使用Collections.synchronizedMap()方法實(shí)現(xiàn)線(xiàn)程安全操作
package cn.lzrabbit.structure.lru; import java.util.LinkedHashMap; import java.util.Map; /** * Created by liuzhao on 14-5-15. */ public class LRUCache2<K, V> extends LinkedHashMap<K, V> { private final int MAX_CACHE_SIZE; public LRUCache2(int cacheSize) { super((int) Math.ceil(cacheSize / 0.75) + 1, 0.75f, true); MAX_CACHE_SIZE = cacheSize; } @Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() > MAX_CACHE_SIZE; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Map.Entry<K, V> entry : entrySet()) { sb.append(String.format("%s:%s ", entry.getKey(), entry.getValue())); } return sb.toString(); } }
這樣算是比較標(biāo)準(zhǔn)的實(shí)現(xiàn)吧,實(shí)際使用中這樣寫(xiě)還是有些繁瑣,更實(shí)用的方法時(shí)像下面這樣寫(xiě),省去了單獨(dú)見(jiàn)一個(gè)類(lèi)的麻煩
final int cacheSize = 100; Map<String, String> map = new LinkedHashMap<String, String>((int) Math.ceil(cacheSize / 0.75f) + 1, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<String, String> eldest) { return size() > cacheSize; } };
LRU緩存LinkedHashMap(delegation)實(shí)現(xiàn)
delegation方式實(shí)現(xiàn)更加優(yōu)雅一些,但是由于沒(méi)有實(shí)現(xiàn)Map接口,所以線(xiàn)程同步就需要自己搞定了
package cn.lzrabbit.structure.lru; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; /** * Created by liuzhao on 14-5-13. */ public class LRUCache3<K, V> { private final int MAX_CACHE_SIZE; private final float DEFAULT_LOAD_FACTOR = 0.75f; LinkedHashMap<K, V> map; public LRUCache3(int cacheSize) { MAX_CACHE_SIZE = cacheSize; //根據(jù)cacheSize和加載因子計(jì)算hashmap的capactiy,+1確保當(dāng)達(dá)到cacheSize上限時(shí)不會(huì)觸發(fā)hashmap的擴(kuò)容, int capacity = (int) Math.ceil(MAX_CACHE_SIZE / DEFAULT_LOAD_FACTOR) + 1; map = new LinkedHashMap(capacity, DEFAULT_LOAD_FACTOR, true) { @Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() > MAX_CACHE_SIZE; } }; } public synchronized void put(K key, V value) { map.put(key, value); } public synchronized V get(K key) { return map.get(key); } public synchronized void remove(K key) { map.remove(key); } public synchronized Set<Map.Entry<K, V>> getAll() { return map.entrySet(); } public synchronized int size() { return map.size(); } public synchronized void clear() { map.clear(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Map.Entry entry : map.entrySet()) { sb.append(String.format("%s:%s ", entry.getKey(), entry.getValue())); } return sb.toString(); } }
LRU Cache的鏈表+HashMap實(shí)現(xiàn)
注:此實(shí)現(xiàn)為非線(xiàn)程安全,若在多線(xiàn)程環(huán)境下使用需要在相關(guān)方法上添加synchronized以實(shí)現(xiàn)線(xiàn)程安全操作
package cn.lzrabbit.structure.lru; import java.util.HashMap; /** * Created by liuzhao on 14-5-12. */ public class LRUCache1<K, V> { private final int MAX_CACHE_SIZE; private Entry first; private Entry last; private HashMap<K, Entry<K, V>> hashMap; public LRUCache1(int cacheSize) { MAX_CACHE_SIZE = cacheSize; hashMap = new HashMap<K, Entry<K, V>>(); } public void put(K key, V value) { Entry entry = getEntry(key); if (entry == null) { if (hashMap.size() >= MAX_CACHE_SIZE) { hashMap.remove(last.key); removeLast(); } entry = new Entry(); entry.key = key; } entry.value = value; moveToFirst(entry); hashMap.put(key, entry); } public V get(K key) { Entry<K, V> entry = getEntry(key); if (entry == null) return null; moveToFirst(entry); return entry.value; } public void remove(K key) { Entry entry = getEntry(key); if (entry != null) { if (entry.pre != null) entry.pre.next = entry.next; if (entry.next != null) entry.next.pre = entry.pre; if (entry == first) first = entry.next; if (entry == last) last = entry.pre; } hashMap.remove(key); } private void moveToFirst(Entry entry) { if (entry == first) return; if (entry.pre != null) entry.pre.next = entry.next; if (entry.next != null) entry.next.pre = entry.pre; if (entry == last) last = last.pre; if (first == null || last == null) { first = last = entry; return; } entry.next = first; first.pre = entry; first = entry; entry.pre = null; } private void removeLast() { if (last != null) { last = last.pre; if (last == null) first = null; else last.next = null; } } private Entry<K, V> getEntry(K key) { return hashMap.get(key); } @Override public String toString() { StringBuilder sb = new StringBuilder(); Entry entry = first; while (entry != null) { sb.append(String.format("%s:%s ", entry.key, entry.value)); entry = entry.next; } return sb.toString(); } class Entry<K, V> { public Entry pre; public Entry next; public K key; public V value; } }
LinkedHashMap的FIFO實(shí)現(xiàn)
FIFO是First Input First Output的縮寫(xiě),也就是常說(shuō)的先入先出,默認(rèn)情況下LinkedHashMap就是按照添加順序保存,我們只需重寫(xiě)下removeEldestEntry方法即可輕松實(shí)現(xiàn)一個(gè)FIFO緩存,簡(jiǎn)化版的實(shí)現(xiàn)代碼如下
final int cacheSize = 5; LinkedHashMap<Integer, String> lru = new LinkedHashMap<Integer, String>() { @Override protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) { return size() > cacheSize; } };
調(diào)用示例
測(cè)試代碼
package cn.lzrabbit.structure.lru; import cn.lzrabbit.ITest; import java.util.LinkedHashMap; import java.util.Map; /** * Created by liuzhao on 14-5-15. */ public class LRUCacheTest { public static void main(String[] args) throws Exception { System.out.println("start..."); lruCache1(); lruCache2(); lruCache3(); lruCache4(); System.out.println("over..."); } static void lruCache1() { System.out.println(); System.out.println("===========================LRU 鏈表實(shí)現(xiàn)==========================="); LRUCache1<Integer, String> lru = new LRUCache1(5); lru.put(1, "11"); lru.put(2, "11"); lru.put(3, "11"); lru.put(4, "11"); lru.put(5, "11"); System.out.println(lru.toString()); lru.put(6, "66"); lru.get(2); lru.put(7, "77"); lru.get(4); System.out.println(lru.toString()); System.out.println(); } static <T> void lruCache2() { System.out.println(); System.out.println("===========================LRU LinkedHashMap(inheritance)實(shí)現(xiàn)==========================="); LRUCache2<Integer, String> lru = new LRUCache2(5); lru.put(1, "11"); lru.put(2, "11"); lru.put(3, "11"); lru.put(4, "11"); lru.put(5, "11"); System.out.println(lru.toString()); lru.put(6, "66"); lru.get(2); lru.put(7, "77"); lru.get(4); System.out.println(lru.toString()); System.out.println(); } static void lruCache3() { System.out.println(); System.out.println("===========================LRU LinkedHashMap(delegation)實(shí)現(xiàn)==========================="); LRUCache3<Integer, String> lru = new LRUCache3(5); lru.put(1, "11"); lru.put(2, "11"); lru.put(3, "11"); lru.put(4, "11"); lru.put(5, "11"); System.out.println(lru.toString()); lru.put(6, "66"); lru.get(2); lru.put(7, "77"); lru.get(4); System.out.println(lru.toString()); System.out.println(); } static void lruCache4() { System.out.println(); System.out.println("===========================FIFO LinkedHashMap默認(rèn)實(shí)現(xiàn)==========================="); final int cacheSize = 5; LinkedHashMap<Integer, String> lru = new LinkedHashMap<Integer, String>() { @Override protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) { return size() > cacheSize; } }; lru.put(1, "11"); lru.put(2, "11"); lru.put(3, "11"); lru.put(4, "11"); lru.put(5, "11"); System.out.println(lru.toString()); lru.put(6, "66"); lru.get(2); lru.put(7, "77"); lru.get(4); System.out.println(lru.toString()); System.out.println(); } }
運(yùn)行結(jié)果
"C:\Program Files (x86)\Java\jdk1.6.0_10\bin\java" -Didea.launcher.port=7535 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 13.0.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\charsets.jar;C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\deploy.jar;C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\javaws.jar;C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\jce.jar;C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\jsse.jar;C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\management-agent.jar;C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\plugin.jar;C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\resources.jar;C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\rt.jar;C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\ext\dnsns.jar;C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\ext\localedata.jar;C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\ext\sunjce_provider.jar;C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\ext\sunmscapi.jar;C:\Program Files (x86)\Java\jdk1.6.0_10\jre\lib\ext\sunpkcs11.jar;D:\SVN\projects\Java\Java.Algorithm\target\test-classes;D:\SVN\projects\Java\Java.Algorithm\target\classes;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 13.0.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain Main start... ===========================LRU 鏈表實(shí)現(xiàn)=========================== 5:11 4:11 3:11 2:11 1:11 4:11 7:77 2:11 6:66 5:11 ===========================LRU LinkedHashMap(inheritance)實(shí)現(xiàn)=========================== 1:11 2:11 3:11 4:11 5:11 5:11 6:66 2:11 7:77 4:11 ===========================LRU LinkedHashMap(delegation)實(shí)現(xiàn)=========================== 1:11 2:11 3:11 4:11 5:11 5:11 6:66 2:11 7:77 4:11 ===========================FIFO LinkedHashMap默認(rèn)實(shí)現(xiàn)=========================== {1=11, 2=11, 3=11, 4=11, 5=11} {3=11, 4=11, 5=11, 6=66, 7=77} over... Process finished with exit code 0
到此這篇關(guān)于詳解Java實(shí)現(xiàn)LRU緩存的文章就介紹到這了,更多相關(guān)Java實(shí)現(xiàn)LRU緩存內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java集合collection接口與子接口及實(shí)現(xiàn)類(lèi)
這篇文章主要介紹了java集合collection接口與子接口及實(shí)現(xiàn)類(lèi),文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-07-07Mybatis-Plus字段策略FieldStrategy的使用
本文主要介紹了Mybatis-Plus字段策略FieldStrategy的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08SpringBoot 并發(fā)登錄人數(shù)控制的實(shí)現(xiàn)方法
這篇文章主要介紹了SpringBoot 并發(fā)登錄人數(shù)控制的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05解決java Graphics drawImage 無(wú)法顯示圖片的問(wèn)題
這篇文章主要介紹了解決java Graphics drawImage 無(wú)法顯示圖片的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11解決執(zhí)行Junit單元測(cè)試報(bào)錯(cuò)java.lang.ClassNotFoundException問(wèn)題
這篇文章主要介紹了解決執(zhí)行Junit單元測(cè)試報(bào)錯(cuò)java.lang.ClassNotFoundException問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11