"Source code" LRUCache Source code anatomy

Source: Internet
Author: User

The previous article analyzed the Linkedhashmap source code, which is in addition to most of the features of HashMap. It also features linked lists, which are able to maintain the traversal order consistent with the insertion order.

Other than that. When we set Accessorder to true. To make the traversal sequence consistent with the order of access, the internal doubly linked list will arrange the entry object in the order of the most recent access to the most recent interview , which can be used for caching.


This article analyzes the LRUCache is not the JDK class, but from Android, familiar with the Android memory cache must be unfamiliar to this class.

LRUCache internal maintenance is a linkedhashmap. The following begins the analysis of LRUCache. Note: The following LRUCache source code is from the SUPPORT.V4 package.

The first is the member variables of this class:

Private final linkedhashmap<k, v> map;    /** Size of this cache in units. Not necessarily the number of elements. */    private int size;//current size    private int maxsize;//max capacity    private int putcount;//put times    private int Createcount;//create times    Private int evictioncount;//number of recoveries    private int hitcount;//hit count    private int misscount;//missing Times
the initialization of the LINKEDHASHMAP is placed in the constructor:
Public LruCache (int maxSize) {        if (maxSize <= 0) {            throw new IllegalArgumentException ("maxSize <= 0");        }        this.maxsize = maxSize;        This.map = new linkedhashmap<k, v> (0, 0.75f, true);    }

This sets the Accessorder of Linkedhashmap to True.

Next look at the two most important methods, put and get.

The first is the put method:

Public final V put (K key, V value) {        if (key = = NULL | | value = = NULL) {//Key value does not agree to null            throw new NullPointerException (" Key = = NULL | | Value = = null ");        }        V previous;        Synchronized (this) {//thread-safe            putcount++;            Size + = safesizeof (key, value);            Previous = Map.put (key, value);            if (previous! = NULL) {//has been inserted before the same key                size-= safesizeof (key, previous);//Then minus the capacity of the entry, due to overwrite            }        }        if (previous! = null) {            entryremoved (false, key, previous, value);//This method defaults to NULL implementation        }        TrimToSize ( maxSize);//If the capacity exceeds MaxSize, the entry return previous with very little recent visits will be removed        ;    
The Put method is nothing more than calling Linkedhashmap's put method. However, before invoking the put method of Linkedhashmap, it is inferred that key and value are null, which meansLRUCache does not agree with null key value。

In addition, put operation is locked, so it is thread-safe ! Since it is a cache, it is necessary to dynamically delete some infrequently used key-value pairs, the work is completed by the TrimToSize method:

public void TrimToSize (int. maxSize) {while (true) {///constantly delete Linkedhashmap header entry, which is the least recently visited entry.            Until size is less than the maximum capacity K key;            V value; Synchronized (this) {//thread-safe if (Size < 0 | | (Map.isempty () && size! = 0)) {throw new IllegalStateException (GetClass (). GetName () + ". SizeOf () is Repor                Ting inconsistent results! ");}                if (size <= maxSize | | map.isempty ()) {//until capacity is less than maximum capacity break; } map.entry<k, v> toevict = Map.entryset (). iterator (). Next ();//point to the list header key = Toevict.get                Key ();                Value = Toevict.getvalue ();                Map.Remove (key);//delete the least visited entry size-= Safesizeof (key, value);            evictioncount++;        } entryremoved (True, key, value, NULL); }    }

This method constantly loops through the list header elements. This is the least recently visited element until the capacity does not exceed the pre-defined maximum value. Note: LRUCache also has a LRUCache class in the Android.util package, but I find that the TrimToSize method of this class is wrong:
private void trimtosize (int maxSize) {while (true) {K key;            V value; Synchronized (this) {if (Size < 0 | | (Map.isempty () && size! = 0)) {throw new IllegalStateException (GetClass (). GetName () + ". SizeOf () is Repor                Ting inconsistent results! ");}                if (size <= maxSize) {break;                } map.entry<k, v> toevict = null;                For (Map.entry<k, v> entry:map.entrySet ()) {toevict = Entry;                } if (toevict = = null) {break;                } key = Toevict.getkey ();                Value = Toevict.getvalue ();                Map.Remove (key);                Size-= safesizeof (key, value);            evictioncount++;        } entryremoved (True, key, value, NULL); }    }
the code here will loop through the tail of the list, which is the most recently visited element, which is wrong! So everyone in the memory cache must pay attention to see if there is a problem with the TrimToSize method.
Next is the Get method:
Public final V get (K key) {if (key = = null) {//Disagree with null key throw new NullPointerException ("key = = null");        } V Mapvalue;                Synchronized (this) {//thread safe Mapvalue = Map.get (key);//Call Linkedhashmap's Get method if (mapvalue! = null) {        hitcount++;//hit count plus 1 return mapvalue;//returns value} misscount++;//miss        } V Createdvalue = Create (key);//default return is False if (Createdvalue = = null) {return null; } synchronized (this) {createcount++;//assumes the creation was successful, then the Create number plus 1 Mapvalue = Map.put (Key, Createdva                Lue);//Put into the hash table if (mapvalue! = null) {//There was a conflict so undo the last put            Map.put (key, Mapvalue);            } else {size + safesizeof (key, Createdvalue);            }} if (Mapvalue! = null) {entryremoved (False, Key, Createdvalue, Mapvalue); Return MAPVALue            } else {trimtosize (maxSize);        return createdvalue; }    }

The Get method is thread-safe by looking for the corresponding value in Linkedhashmap based on key.
The above is the most important part of LRUCache, and then look at the other methods: remove:
  Public final V Remove (K key) {        if (key = = null) {            throw new NullPointerException ("key = = null");        }        V previous;        Synchronized (this) {            previous = Map.Remove (key);//Call the Remove method of Linkedhashmap            if (previous! = null) {                Size-= Safesizeof (key, previous);            }        }        if (previous! = null) {            entryremoved (false, key, previous, NULL);        }        Return previous;//returns value    }

sizeof:This method is used to calculate the size of each entry, and the subclass must replicate the class.
protected int sizeOf (K key, V value) {//used to calculate the size of each entry        return 1;    }
Snapshot method,returns the entire collection of entries in the current cache
Public synchronized final map<k, v> snapshot () {        return new linkedhashmap<k, v> (MAP);    }

Summary:the 1.LruCache encapsulates the Linkedhashmap. Provides the capabilities of the LRU cache;2.LruCache Use the TrimToSize method to proactively delete the most recent key-value pairs. 3.LruCache does not agree with the null key value;4.LruCache thread safety. 5. When inheriting LRUCache, it is necessary to replicate the sizeof method. Used to calculate the size of each entry.






"Source code" LRUCache Source code anatomy

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.