LRU Cache Implementation (Java)

Source: Internet
Author: User

    • Linkedhashmap implementation of LRU cache
    • +hashmap implementation of LRU Cache's linked list
    • FIFO implementation of Linkedhashmap
    • Invoke Example

LRU is least recently used abbreviation, translated is "least recently used", the LRU cache is the use of this principle, the simple is to cache a certain amount of data, when the threshold is exceeded set to remove some outdated data, such as we cache 10,000 of data, When the data is less than 10000 can be added at will, when more than 10000 need to add new data, and to delete the outdated data, to ensure that we cache 10,000, how to determine the deletion of which expired data, the use of the LRU algorithm is the oldest data deleted, nonsense not to say, Below, the Java version of the LRU cache implementation

There are usually two options for implementing LRU caches in Java, one is to use Linkedhashmap, one to design data structures, and to use linked lists +hashmap

Linkedhashmap implementation of LRU cache

LINKEDHASHMAP itself has implemented sequential storage, by default it is stored in the order in which the elements are added, or it can be stored in order of access, that is, the most recently read data is first, the oldest read is placed on the last side, and then it has a method of determining whether to delete the oldest data. The default is to return False, that is, do not delete data, we use Linkedhashmap to implement the LRU cache method is a simple extension of the LINKEDHASHMAP implementation, there are two ways to expand, one is inheritance, one is delegation, How to use the specific way to see a person's preferences

A constructor for Linkedhashmap that, when the parameter Accessorder is true, is sorted in the order of access, most recently visited, and the first accessed is placed behind public linkedhashmap (int Initialcapacity, Float loadfactor, Boolean accessorder) {        super (initialcapacity, loadfactor);        This.accessorder = Accessorder;} Linkedhashmap to determine whether to delete the oldest element method, the default return False, that is, do not delete old data//We have to do is to override this method, when certain conditions are met to delete old data protected Boolean Removeeldestentry (map.entry<k,v> eldest) {        return false;}
LRU Cache Linkedhashmap (inheritance) implementation

The implementation of the inheritance method is relatively simple, and the map interface is implemented, and the Collections.synchronizedmap () method can be used to implement thread-safe operation in multi-threaded environment.

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 ();    }}

This is a more standard implementation, the actual use of such writing or some cumbersome, more practical way to write like the following, eliminating the trouble of seeing a class alone

Final int cacheSize = 100; map<string, string> map = new linkedhashmap<string, string> ((int) Math.ceil (cachesize/0.75f) + 1, 0.75f, Tru e) {    @Override    protected Boolean removeeldestentry (Map.entry<string, string> eldest) {    return size ( > cacheSize;    }};

LRU Cache Linkedhashmap (delegation) implementation

The delegation approach is more elegant, but because the map interface is not implemented, thread synchronization needs to be done by itself.

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; The capactiy,+1 of HashMap is calculated based on the CacheSize and load factor to ensure that hashmap expansion is not triggered when the CacheSize cap is reached, int capacity = (int) Math.ceil (max_cache_si        Ze/default_load_factor) + 1; Map = new Linkedhashmap (capacity, Default_load_factor, true) {@Override protected Boolean Removeeld            Estentry (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 (); }}
+hashmap implementation of LRU Cache's linked list

Note: This implementation is non-thread-safe, and if used in a multithreaded environment, you need to add synchronized on the relevant methods to implement thread-safe operations

Package Cn.lzrabbit.structure.lru;import java.util.hashmap;/** * Created is 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; }}
FIFO implementation of Linkedhashmap

FIFO is the first Input first output of the abbreviation, that is, the Linkedhashmap, by default, is saved in order to add, we only need to rewrite the next Removeeldestentry method to easily implement a FIFO cache , the simplified version of the implementation code is as follows

Final int cacheSize = 5; Linkedhashmap<integer, string> LRU = new Linkedhashmap<integer, string> () {    @Override    protected Boolean removeeldestentry (Map.entry<integer, string> eldest) {    return size () > CacheSize;    }};
Invoke Example

Test code

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 ("sta        RT ... ");        LruCache1 ();        LruCache2 ();        LruCache3 ();             LruCache4 ();    System.out.println ("over ...");        } static void LruCache1 () {System.out.println ();        System.out.println ("===========================LRU linked list Implementation ===========================");        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) Implementation ===========================");        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) Implementation ===========================");        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 default implementation ===========================");        Final int cacheSize = 5; Linkedhashmap<integer, string> LRU = new Linkedhashmap<integer, string> () {@Override PR            otected 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 (); }}

Run results

"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 MAINSTART...===========================LRU linked list implementation =================== ========5:11 4:11 3:11 2:11 1:11 4:11 7:77 2:11 6:66 5:11 ===========================LRU LinkedHashMap(inheritance)实现==== =======================1:11 2:11 3:11 4:11 5:11 5:11 6:66 2:11 7:77 4:11 ===========================lru LinkedHashMap (del Egation) Implementation ===========================1:11 2:11 3:11 4:11 5:11 5:11 6:66 2:11 7:77 4:11 ===========================fifo Li Nkedhashmap default implementation ==========================={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

LRU Cache Implementation (Java)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.