<span id="Label3"></p> <blockquote> <blockquote> <p>I think in writing about the data structure or algorithm implementation class source parsing blog, should not be eager to talk about its use or immediately expand the parsing of the source code, but first to explain the data structure or algorithm, understand its design, and then from its design to talk about how to achieve, finally from the perspective of the realization of the source, In order to understand Deeply. This is the latest reading of some blog after thinking. If you have other ideas about this issue, please feel free to exchange Messages.</p> </blockquote> </blockquote>Lru<p><p>Before we read the LRUCache source code, Let's look at what's here <code>Lru</code> . <code>LRU</code>All <code>Least Recently Used</code> -in-one, Least recently used, is a cache substitution algorithm. Our cache capacity is limited and it faces a problem: when new content needs to be added to our cache, but our cache is free of space to put in new content, how to discard the original part of the content to make room for new Content. There are many algorithms to solve this problem, such as Lru,lfu,fifo and so On.<br>It is important to distinguish between the <code>LRU</code> and <code>LFU</code> . The former is the least recently used, that is, the object that is not used for the longest time, and the latter is the least used recently, that is, the least used object for a period of Time. For example, the order in which we cache objects is: a b C b D a C a, when an object needs to be eliminated, if the LRU algorithm is used, then the elimination is b, because it is the longest time not used. If the LFU algorithm is used, then D is eliminated because it is used only once and is the least frequently used during this time period.<br><code>LRU</code>Once we know, let's look at how LRUCache is Implemented.</p></p>Linkedhashmap<p><p>Let's look at <code>LruCache</code> the structure, its member variables and the construction method are defined as follows (here is the code in android-23):</p></p><pre class="prettyprint"><code class="language-java hljs "> <span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Final</span></span>linkedhashmap<k, v> map;<span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">int</span></span>Size<span class="hljs-comment"><span class="hljs-comment">//the size of the current cache Content. It is not necessarily the number of elements, such as if the cache is a picture, the general use of image memory size</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">int</span></span>maxSize;<span class="hljs-comment"><span class="hljs-comment">//maximum cacheable Size</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">int</span></span>putcount;<span class="hljs-comment"><span class="hljs-comment">//the number of times the put method was called</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">int</span></span>createcount;<span class="hljs-comment"><span class="hljs-comment">the number of times the create (Object) was called</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">int</span></span>evictioncount;<span class="hljs-comment"><span class="hljs-comment">//the number of elements that have been swapped out</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">int</span></span>hitCount;<span class="hljs-comment"><span class="hljs-comment">The//get method hits the number of elements in the cache</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">int</span></span>misscount;<span class="hljs-comment"><span class="hljs-comment">The//get Method misses the number of elements in the cache</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-title"><span class="hljs-title">LruCache</span></span>(<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>MaxSize) {<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(maxSize <=<span class="hljs-number"><span class="hljs-number">0</span></span>) {<span class="hljs-keyword"><span class="hljs-keyword">Throw</span></span> <span class="hljs-keyword"><span class="hljs-keyword">New</span></span>IllegalArgumentException (<span class="hljs-string"><span class="hljs-string">"maxSize <= 0"</span></span>); }<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>. maxSize = maxSize;<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>. Map =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>linkedhashmap<k, v> (<span class="hljs-number"><span class="hljs-number">0</span></span>,<span class="hljs-number"><span class="hljs-number">0.75</span></span>F<span class="hljs-keyword"><span class="hljs-keyword">true</span></span>); }</code></pre><p><p>From the definition above, it is found that the contents of the LRUCache cache are placed in <code>LinkedHashMap</code> the Object. so, <code>LinkedHashMap</code> What is it? How does it implement <code>LRU</code> this caching strategy?</p></p><p><p><code>LinkedHashMap</code>Inherited from <code>HashMap</code> , the difference is that it is a two-way circular linked list, each of its data nodes have two pointers, respectively, pointing to direct precursor and direct successor, which we can see from its inner class <code>LinkedEntry</code> , which is defined as Follows:</p></p><pre class="prettyprint"><code class="language-java hljs "> <span class="hljs-keyword"><span class="hljs-keyword">Static</span></span>Class linkedentry<k, v> extends hashmapentry<k, v> {linkedentry<k, v> nxt; linkedentry<k, v> prv;<span class="hljs-javadoc"><span class="hljs-javadoc">/** Create The header entry *</span> /</span>Linkedentry () {<span class="hljs-keyword"><span class="hljs-keyword">Super</span></span>(<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>,<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>,<span class="hljs-number"><span class="hljs-number">0</span></span>,<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>); NXT = PRV =<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>; }<span class="hljs-javadoc"><span class="hljs-javadoc">/** Create A normal entry *</span> /</span>Linkedentry (K key, V value,<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>hash, hashmapentry<k, v> next, linkedentry<k, v> nxt, linkedentry<k, v> prv) {<span class="hljs-keyword"><span class="hljs-keyword">Super</span></span>(key, value, hash, next);<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>. NXT = nxt;<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>. PRV = prv; } }</code></pre><p><p><code>LinkedHashMap</code>The data structure of the two-way cyclic linked list is implemented, and it is defined as Follows:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class="language-java hljs"><span class="hljs-keyword">public </span> <span class="hljs-class"><span class="hljs-keyword">class </span> <span class="hljs-title">linkedhashmap </span> <<span class="hljs-title">k </span>, <span class="hljs-title">v </span> > <span class="hljs-keyword">extends </span> Span class= "hljs-title" >hashmap </span> <<span class="hljs-title">k </span>, <span class="hljs-title">v </span> > { <span class="hljs-keyword">transient </span> linkedentry<k, v> header; <span class="hljs-keyword">private </span> <span class="hljs-keyword">final </span> <span class="hljs-keyword">boolean </span> accessorder;} </code> </pre></pre><p><p>When a linked list is not empty, <code>header.nxt</code> point to the first node, point to the <code>header.prv</code> last node, and point to itself when the list is empty <code>header.nxt</code> <code>header.prv</code> .<br><code>accessOrder</code>is to specify how it is sorted, when it is <code>false</code> , only in the order in which it is inserted, i.e. the new order is placed at the end of the list, and when it is <code>true</code> <strong>updated or accessed</strong> by the data of a node, the corresponding node is also placed at the Tail. It assigns values by constructing methods <code>public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)</code> .<br>Let's take a look at the method execution process when adding a new node:</p></p><pre class="prettyprint"><code class="language-java hljs "> <span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span>Addnewentry (K key, V value,<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>Hash<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>Index) {linkedentry<k, v> Header =<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>. header;<span class="hljs-comment"><span class="hljs-comment">//Remove eldest entry if instructed</span> to does So.</span>linkedentry<k, v> eldest = header.nxt;<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(eldest! = Header && removeeldestentry (eldest)) {remove (eldest.key); }<span class="hljs-comment"><span class="hljs-comment">//Create New entry, link it on to list, and put it into table</span></span>linkedentry<k, v> oldtail = header.prv; linkedentry<k, v> Newtail =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>linkedentry<k,v> (key, value, hash, table[index], header, oldtail); table[index] = OLDTAIL.NXT = HEADER.PRV = newtail; }</code></pre><p><p>As you can see, when a new node is added, the structure is as follows:<br></p></p><p><p>When <code>accessOrder</code> <code>true</code> a node is updated or accessed, it moves the node to the tail and the corresponding code is as Follows:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class="language-java hljs "> <span class="hljs-keyword">private</span><span class="hljs-keyword">void</span><span class="hljs-title">makeTail</span>(LinkedEntry<K, V> e) { <span class="hljs-comment">// Unlink e</span> e.prv.nxt = e.nxt; e.nxt.prv = e.prv; <span class="hljs-comment">// Relink e as tail</span> <span class="hljs-keyword">this</span>.header; LinkedEntry<K, V> oldTail = header.prv; e.nxt = header; e.prv = oldTail; oldTail.nxt = header.prv = e; modCount++; }</code></pre></pre><p><p>The above code is divided into two steps, the first step is to first remove the node (Unlink e), such as:<br></p></p><p><p>The second step is to move this node to the tail (relink e as tail), which is to point the old tail <code>nxt</code> and head to <code>prv</code> it, and let it point to the <code>nxt</code> head, and point it to the <code>prv</code> old Tail. Such as:<br></p></p><p><p>In addition, <code>LinkedHashMap</code> a method is provided <code>public Entry<K, V> eldest()</code> that returns the oldest node, when it is <code>accessOrder</code> , the <code>true</code> <strong>least recently used</strong> Node.</p></p>LruCache<p><p>When we are familiar with <code>LinkedHashMap</code> it, we find that it <code>Lru</code> becomes a matter of course to implement the algorithm through it. All we need to do is to define the maximum size of the cache, record the current size of the cache, and check to see if the maximum size is exceeded when new data is Placed. Therefore <code>LruCache</code> , the following three required member variables are defined:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class="language-java hljs "> <span class="hljs-keyword">private</span><span class="hljs-keyword">final</span> LinkedHashMap<K, V> map; <span class="hljs-javadoc">/** Size of this cache in units. Not necessarily the number of elements. */</span> <span class="hljs-keyword">private</span><span class="hljs-keyword">int</span> size; <span class="hljs-keyword">private</span><span class="hljs-keyword">int</span> maxSize;</code></pre></pre><p><p>Then let's read it's get method:</p></p><pre class="prettyprint"><code class="language-java hljs "> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">Final</span></span>V<span class="hljs-title"><span class="hljs-title">Get</span></span>(K Key) {<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(key = =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {<span class="hljs-keyword"><span class="hljs-keyword">Throw</span></span> <span class="hljs-keyword"><span class="hljs-keyword">New</span></span>NullPointerException (<span class="hljs-string"><span class="hljs-string">"key = = null"</span></span>); } V mapvalue;<span class="hljs-keyword"><span class="hljs-keyword">synchronized</span></span>(<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>) {mapvalue = Map.get (key);<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(mapvalue! =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {<span class="hljs-comment"><span class="hljs-comment">//when The corresponding value can be obtained, the value is returned</span></span>hitcount++;<span class="hljs-keyword"><span class="hljs-keyword">return</span></span>mapvalue; } misscount++; }<span class="hljs-comment">/ <span class="hljs-comment">* * Attempt to create a Value. This is a long time, and the map * May is different when create () Returns. If a conflicting value is * added to the map while create () is working, we leave that value in * the map and release the created Value. */</span></span> <span class="hljs-comment"><span class="hljs-comment">//try to create a value, the default implementation of this method is to return null DIRECTLY. In its design, however, the map has changed since the method might have been executed. </span></span>V Createdvalue = Create (key);<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(createdvalue = =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {<span class="hljs-comment"><span class="hljs-comment">//if You do not create a new value for a key that is not named, return directly</span></span> <span class="hljs-keyword"><span class="hljs-keyword">return</span></span> <span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>; }<span class="hljs-keyword"><span class="hljs-keyword">synchronized</span></span>(<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>) {createcount++;<span class="hljs-comment"><span class="hljs-comment">//put The created value in the map, and if the map is exactly in the previous procedure, it will return the values placed in the Key-value</span> .</span>Mapvalue = Map.put (key, createdvalue);<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(mapvalue! =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {<span class="hljs-comment"><span class="hljs-comment">//if not empty, the description does not need the value we created, so we put the returned value in</span></span> <span class="hljs-comment"><span class="hljs-comment">//there is a conflict so undo</span> the last put</span>Map.put (key, mapvalue); }<span class="hljs-keyword"><span class="hljs-keyword">Else</span></span>{size + = safesizeof (key, createdvalue);<span class="hljs-comment"><span class="hljs-comment">//is empty, indicating that we have updated the value of this key and need to</span> recalculate the size</span>} }<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(mapvalue! =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {<span class="hljs-comment"><span class="hljs-comment">//the value placed above has a conflict</span></span>Entryremoved (<span class="hljs-keyword"><span class="hljs-keyword">false</span></span>, key, createdvalue, mapvalue);<span class="hljs-comment"><span class="hljs-comment">//notification The value created before has been removed and changed to Mapvalue</span></span> <span class="hljs-keyword"><span class="hljs-keyword">return</span></span>mapvalue; }<span class="hljs-keyword"><span class="hljs-keyword">Else</span></span>{trimtosize (maxSize);<span class="hljs-comment"><span class="hljs-comment">//no conflict, The size has changed because the newly created value has been placed, so the size needs to be trimmed</span></span> <span class="hljs-keyword"><span class="hljs-keyword">return</span></span>createdvalue; } }</code></pre><p><p><code>LruCache</code>is likely to be accessed by multiple threads at the same time, so locks are made when reading and writing <code>map</code> . When the corresponding value is not obtained <code>key</code> , it calls its <code>create(K key)</code> method, which is used to calculate the value of a key when the cache is not named, and its default implementation is to return null DIRECTLY. This method does not add a synchronous lock, which is when it is created, it <code>map</code> may have changed.<br>So in the Get method, if <code>create(key)</code> The returned V is not <code>null</code> , it will be put into the <code>map</code> , and check whether it was created during the creation of other objects have also been created and put <code>map</code> in, if any, will discard the created object, and the previous object left, otherwise, because we put the newly created value, we want to calculate the current size and proceed <code>trimToSize</code> .<br><code>trimToSize</code>The method is based on the incoming maxsize, if the current size exceeds this maxsize, the <strong>oldest node will be removed until it is not exceeded</strong> . The code is as Follows:</p></p><pre class="prettyprint"><code class="language-java hljs "> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">TrimToSize</span></span>(<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>MaxSize) {<span class="hljs-keyword"><span class="hljs-keyword"></span> while</span>(<span class="hljs-keyword"><span class="hljs-keyword">true</span></span>) {K key; V value;<span class="hljs-keyword"><span class="hljs-keyword">synchronized</span></span>(<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>) {<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(size <<span class="hljs-number"><span class="hljs-number">0</span></span>|| (map.isempty () && size! =<span class="hljs-number"><span class="hljs-number">0</span></span>)) {<span class="hljs-keyword"><span class="hljs-keyword">Throw</span></span> <span class="hljs-keyword"><span class="hljs-keyword">New</span></span>IllegalStateException (getclass (). getName () +<span class="hljs-string"><span class="hljs-string">". sizeOf () is reporting inconsistent results!"</span></span>); }<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(size <= MaxSize) {<span class="hljs-keyword"><span class="hljs-keyword"></span> break</span>; } map.entry<k, v> toevict = map.eldest ();<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(toevict = =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {<span class="hljs-keyword"><span class="hljs-keyword"></span> break</span>; } key = Toevict.getkey (); Value = Toevict.getvalue (); Map.Remove (key); size-= safesizeof (key, value); evictioncount++; } entryremoved (<span class="hljs-keyword"><span class="hljs-keyword">true</span></span>, key, value,<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>); } }</code></pre><p><p>next, Let's look at the put method, and its code is simple:</p></p><pre class="prettyprint"><code class="language-java hljs "> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">Final</span></span>V<span class="hljs-title"><span class="hljs-title">put</span></span>(K key, V Value) {<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(key = =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>|| Value = =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {<span class="hljs-keyword"><span class="hljs-keyword">Throw</span></span> <span class="hljs-keyword"><span class="hljs-keyword">New</span></span>NullPointerException (<span class="hljs-string"><span class="hljs-string">"key = = NULL | | Value = = NULL "</span></span>); } V previous;<span class="hljs-keyword"><span class="hljs-keyword">synchronized</span></span>(<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>) {putcount++; Size + = safesizeof (key, value); previous = Map.put (key, value);<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(previous! =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {size-= safesizeof (key, previous); } }<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(previous! =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {entryremoved (<span class="hljs-keyword"><span class="hljs-keyword">false</span></span>, key, previous, value); } trimtosize (maxSize);<span class="hljs-keyword"><span class="hljs-keyword">return</span></span>Previous }</code></pre><p><p>The main logic is to calculate the newly added size, add the sizes, and then put the key-value into the map, if the old data is updated (it <code>map.put(key, value)</code> will return the previous value), subtract the old data size, and call the <code>entryRemoved(false, key, previous, value)</code> method to notify the old data to be updated to the new value, and finally the call <code>trimToSize(maxSize)</code>size of the trimming Cache.<br>The rest of the methods, such as deleting objects inside or resizing them, are logically similar to the ones above, which are skipped here. LRUCache also defines a number of variables for statistical cache hit ratios, which are not discussed here.</p></p>Conclusion<p><p>LRUCache Source Analysis is here, its implementation of the LRU algorithm is mainly through <code>LinkedHashMap</code> to Complete. In addition, using the LRU algorithm, we need to set the maximum size of the cache, and the size of the cache object in different cache types of calculation method is different, the calculation method by <code>protected int sizeOf(K key, V value)</code> implementation, where the default implementation is the number of elements Stored. For example, if we were to cache a bitmap object, we would need to override this method and return the sum of the memory size of all the pixels of the bitmap object. also, LRUCache in the implementation of the multi-threaded access to consider the problem, so when the map is updated, will be added to the synchronization lock.</p></p><p><p>LRUCache is the implementation of a memory cache of the LRU policy, based on which we can implement our own image caches or other Caches. In addition to the memory cache of the LRU algorithm implementation, Google in the subsequent system source code has also been added to the implementation of the Algorithm's disk cache, currently in the android-23 example <strong>displayingbitmaps</strong> , there are corresponding source code <code>DiskLruCache.java</code> . By the way, the <strong>specific</strong> example of how to use LRUCache to implement a picture memory cache can also be referenced in the sample code provided by Google <code>ImageCache.java</code> .</p></p><p><p>In addition, the long-winded: LRU cache policy, Image caching is not without policy, weak references and soft references is not a variety of image frames before the popular memory caching technology, garbage collection mechanism is more inclined to recover weak references and soft reference objects this is not Appropriate.</p></p><p><p>Reference Documents:<br>"cache" Wikipedia: https://zh.wikipedia.org/wiki/%E7%BC%93%E5%AD%98</p></p><p><p>Friendship proofreading: Cold Maple</p></p> <p><p>Android Source Code Parsing--lrucache</p></p></span>
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