In our mobile application development, we often encounter big data access, we usually consider the following aspects of the situation. First, the mobile phone memory restrictions must also ensure that the application of the smooth response; second, as small as possible the flow of consumption, otherwise, your application fluency and good experience again, users will not hesitate to uninstall your application. In the case of big data volume access, the data cache is a solution that we will definitely consider. And as a cache, we are very important to consider the following points: 1. Access speed; 2. Drive out of the old cache policy; 3. It is best to consider a certain degree of concurrency. In this article we mainly talk about the implementation of the algorithm of the LRU cache, we use picture caching as an example to discuss the cache implementation in Android application development.
First, let's take a look at Google's official recommended cache: The Android3.0 joins the LRUCache and Disklrucache (hard disk cache structure) classes. We know from the implementation of the code that the implementations of the LRUCache and Disklrucache caches are implemented based on the Linkedhashmap collection of JDK. Let's start with the analysis of Linkedhashmap's source code.
Through the source we know that Linkedhashmap is inherited hashmap, the underlying structure not only uses HashMap to save elements, but also through the inheritance Hashmapentry implementation of the structure of the doubly linked list to associate other elements. Let's take a look at the node implementation of Linkedhashmap:
/** * linkedhashmap entry. * /private static class Entry<k,v> extends Hashmap.entry<k,v> { //These fields comprise the doubly Li nked list used for iteration. Entry<k,v> before, after;
The Linkedhashmap node entry inherits from the Hashmap.entry, adding two references to the previous element and the latter element, respectively. The implementation of LINKEDHASHMAP is to increase the structure of the doubly-linked list on the basis of HashMap.
Let's take a look at the initialization of the Linkedhashmap, where we see the most constructor parameters:
/** * Constructs an empty <tt>LinkedHashMap</tt> instance with the * specified initial capacity, load Factor and ordering mode. * * @param initialcapacity The initial capacity * @param loadfactor The load factor * @param Accessorder The ordering mode-<tt>true</tt> for * Access-order, <tt>false </tt> for Insertion-order * @throws IllegalArgumentException If the initial capacity is negative * Or the load factor is nonpositive * /public linkedhashmap (int initialcapacity, float loadfactor, boolean Accessorder) { super (initialcapacity, loadfactor); This.accessorder = Accessorder; Accessorder Specifies the sort, default is false, for Fasle, the insertion order is sorted, and the order of the accesses is true when ordering }
We see the initialization method of the overridden base class init practice:
/** * Called by superclass Constructors and Pseudoconstructors (clone, * readobject) before any entries is insert Ed into the map. Initializes * the chain. * /void init () { Header = new entry<k,v> ( -1, NULL, NULL, NULL); Header.before = Header.after = header; }
Here the initialization of the head pointer is given to the loop. Let's take a look at the top two ways to put and get implementations of the collection. We look at the put method first, and the put method of Linkedhashmap does not rewrite the HashMap put method. Just rewrite the AddEntry method under the Put method, the AddEntry method executes when the LINKEDHASHMAP inserts a new node.
/** * This override alters behavior of superclass put method. It causes newly * allocated entry to get inserted at the end of the linked list and * Removes the eldest entry if appropriate. */void AddEntry (int hash, K key, V value, int bucketindex) {createentry (hash, key, value, Bucketindex); Remove eldest entry if instructed, else grow capacity if appropriate entry<k,v> eldest = Header.after; if (Removeeldestentry (eldest)) {Removeentryforkey (Eldest.key); } else {if (size >= threshold) Resize (2 * table.length); }}/** * This override differs from addentry on that it doesn ' t resize the * table or remove the eldest ENT Ry. */void Createentry (int hash, K key, V value, int bucketindex) {hashmap.entry<k,v> old = Table[bucketinde X]; entry<k,v> e = new entry<k,v> (hash, key, value, old); Table[bucketindex] = e; E.addbefore(header); size++; } We look at the way we generate the new node Createntry implementation, we first find the corresponding location on the hash table, and then give the new entry to specify the node before and after. The execution method E.addbefore (header) code is as follows:
/** * Inserts this entry before the specified existing entry in the list. * /private void Addbefore (Entry<k,v> existingentry) {after = existingentry; before = Existingentry.before; Before.after = this; After.before = this; }
We see the code implementation function is to add the new node to the header node before. We go back to AddEntry's code implementation, and we look at entry<k,v> eldest = header.after;if (Removeeldestentry (eldest)), we interpret the post header as our oldest node, Implementation of the Removeeldestentry (eldest) method:
Protected Boolean removeeldestentry (map.entry<k,v> eldest) { return false; }
Removeeldestentry method execution returns false by default, meaning that we do not linkedhashmap the old node by default. We can modify the LRU policy by overriding the Removeeldestentry implementation in the subclass overload. Here we show the execution of the put method with a diagram of the execution of the code:
The first structure before map execution is this:
In order not to let the figures are densely quoted arrows scurrying, I omitted hashmap many entry nodes of the before and after the point, we just focus on the header of the reference point. We Execute Method map.put ("A", "xxx") after the data structure becomes this:
We assign the key 22 node to the back of the EEE using the hash algorithm, and we point the header's before to the node that points to key 22. After analyzing our put method, we then analyze the implementation of the Get method, the code is as follows:
Public V get (Object key) { entry<k,v> e = (entry<k,v>) getentry (key); if (E = = null) return null; E.recordaccess (this); return e.value; }
We see the Get method is very simple, first we go to the map to take the value of the key corresponding to the existence, if not, we return NULL. If present, we execute the e.recoedaccess (this) method.
/** * This method was invoked by the superclass whenever the value * of a pre-existing entry are read by Map.get or Modified by Map.set. * If The enclosing Map is access-ordered, it moves the entry * to the end of the list; otherwise, it does nothing.
*/ void Recordaccess (hashmap<k,v> m) { linkedhashmap<k,v> lm = (linkedhashmap<k,v>) m; if (Lm.accessorder) {//Here the judgment linkedhashmap the sort order lm.modcount++; Remove (); Addbefore (Lm.header); } }
In the Recodeaccess method, when our sort order is false, we exit the method directly in order of insertion sort. When our sort order is to access the sort order, we execute the Remove method, remove the node from the list, and then execute the Addbefore method, we insert the node in front of the header node. In this way, we work on the internship each time according to the access location to sort the operation.
Below we illustrate through the diagram examples, when the Linkedhashmap sort for the access order, we get the process of the operation, LINKEDHASHMAP data structure changes. The code we execute is as follows:
Put.get ("15");//We assume that the value of key 15 corresponds to "BBB"
After we have executed Map.put ("a", "xxx"), the following changes are performed Put.get ("15"):
The above for the implementation of the Get method after the code changes, "BBB" corresponding to the node has not changed, just in the list structure of the pointer changes, so the corresponding iterator access, we read the location is different.
Because we can know that our LRU node is definitely in the header after the point node. When we rewrite Removeeldestentry to modify the LRU policy, we are also the node that was first evicted from the header. We then end up with the following implementation of the Linkedhashmap iterator:
Private abstract class Linkedhashiterator<t> implements iterator<t> {entry<k,v> nextentry = h Eader.after; Entry<k,v> lastreturned = null; /** * The Modcount value, the iterator believes that the backing * List should has. If this expectation are violated, the iterator * has detected concurrent modification. */int expectedmodcount = Modcount; public Boolean Hasnext () {return nextentry! = header; } public void Remove () {if (lastreturned = = null) throw new IllegalStateException (); if (modcount! = expectedmodcount) throw new Concurrentmodificationexception (); LinkedHashMap.this.remove (Lastreturned.key); lastreturned = null; Expectedmodcount = Modcount; } entry<k,v> NextEntry () {if (Modcount! = expectedmodcount) throw new Concurrentmo DIficationexception (); if (NextEntry = = header) throw new Nosuchelementexception (); Entry<k,v> e = lastreturned = NextEntry; NextEntry = E.after; Here we know that our iterator implements the node that the after reference of the access node points to. return e; } } From the implementation of the LINKEDHASHMAP implementation of the iterator inner class linkedhashiterator, the order in which we iterate the elements of our iterators is to begin the iteration from the header node to the after direction. The above is a simple analysis of the LINKEDHASHMAP analysis, the next section we will be for the characteristics of LINKEDHASHMAP data structure, with the LINKEDHASHMAP structure to achieve the advantages of fast buffer access, but also with common open source implementation, For the implementation of a certain concurrent Android down-cache implementation.
Talk about the Android LRU cache algorithm Implementation Learning notes (i)