Concept:
LruCache
What is LRUCache?
What is the LRUCache implementation principle?
These two questions can actually answer as a question, know what is LruCache, only then know the LruCache realization principle; The full name of the LRU is least recently used, the least recently used! So we can infer the principle of LruCache: To remove the least recently used data from the cache, to retain the most frequently used data, how to implement the specific code, we go into the source to see.
LRUCache Source Code Analysis
public class Lrucache<k, v> {//cache map Collection, why use LINKEDHASHMAP//because it is correct to take the cache value after the sort, to ensure//the next removal is the least used value of the PRI Vate final linkedhashmap<k, v> map; The current cached value is private int size; Maximum value private int maxSize; The number of private int putcount added to the cache; The number of created private int createcount; The number of private int evictioncount to be removed; Number of hits private int hitCount; Missing number private int misscount; Instantiate Lru, need to pass in the maximum value of the cache//This maximum value can be a number, such as the number of objects, or the size of the memory//For example, the maximum memory can only cache 5 megabytes public LruCache (int maxSize) {if (max Size <= 0) {throw new IllegalArgumentException ("maxSize <= 0"); } this.maxsize = MaxSize; This.map = new linkedhashmap<k, v> (0, 0.75f, true); }//Resets the value of the maximum cache public void resize (int maxSize) {if (maxSize <= 0) {throw new Illegalargumentexc Eption ("maxSize <= 0"); } synchronized (this) {this.maxsize = maxSize; } trimtosize (MaxSize); } Get cache value from key public final V get (K key) {if (key = = null) {throw new NullPointerException ("key = = null "); } V Mapvalue; Synchronized (this) {Mapvalue = Map.get (key); if (mapvalue! = null) {hitcount++; return mapvalue; } misscount++; }//If not, the user can go to create V createdvalue = "Create" (key); if (Createdvalue = = null) {return null; } synchronized (this) {createcount++; Mapvalue = Map.put (key, Createdvalue); if (mapvalue! = null) {//There is a conflict so undo the last put Map.put (key, Mapvalue) ; } else {//the size of the cache is changed by the sizes + = safesizeof (key, Createdvalue); }}//Not removed here, just changed position if (mapvalue! = null) {entryremoved (False, Key, Createdvalue, Mapval UE); return mapvalue; } else {//Determine if the cache is out of bounds trimtosize (maxSize); return createdvalue; }}//Add the cache to the same public final V put (K key, V value) {if (key = NULL | | value = NULL) as the code after the above method's create {throw new NullPointerException ("key = = NULL | | Value = = null "); } V Previous; Synchronized (this) {putcount++; Size + = safesizeof (key, value); Previous = Map.put (key, value); if (previous! = NULL) {Size-= safesizeof (key, previous); }} if (previous! = null) {entryremoved (False, key, previous, value); } trimtosize (MaxSize); return previous; }//detects if the cache is out of bounds 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 reporting inconsistent results!"); }//If not, returns if (size <= maxSize) {break; }//The following code indicates that the maximum range map.entry<k has been exceeded, v> toevict = null; For (Map.entry<k, v> entry:map.entrySet ()) {toevict = Entry; } if (toevict = = null) {break; }//Remove the last one, which is the least used cache key = Toevict.getkey (); Value = Toevict.getvalue (); Map.Remove (key); Size-= safesizeof (key, value); evictioncount++; } entryremoved (True, key, value, NULL); }}//manual removal, user calls public final V remove (K key) {if (key = = null) {throw new Nullpointerexceptio N ("key = = null"); } V Previous; SynchronIzed (This) {previous = Map.Remove (key); if (previous! = NULL) {Size-= safesizeof (key, previous); }} if (previous! = null) {entryremoved (False, key, previous, NULL); } return previous; }//Here the user can override it for data and memory reclamation operations protected void entryremoved (Boolean evicted, K key, v OldValue, v newvalue) {} protecte D V Create (K key) {return null; } private int safesizeof (K key, V value) {int result = SizeOf (key, value); if (Result < 0) {throw new IllegalStateException ("Negative size:" + key + "=" + value); } return result; }//This method to pay special attention, and we instantiate LruCache maxSize to echo, how to do echo, such as maxSize size for the number of cache, here is the return 1 OK, if it is the size of memory, if 5M, this can not be the number of , this should be the size of each cache value, and if it is Bitmap, this should be bitmap.getbytecount (); protected int sizeOf (K key, V value) {return 1; }//Empty cache public final void Evictall () {trimtosize (-1);//-1 Would evict 0-sized elements} public synchronized final int size () {return size; } public synchronized final int maxSize () {return maxSize; } public synchronized final int HitCount () {return hitCount; } public synchronized final int Misscount () {return misscount; } public synchronized final int Createcount () {return createcount; } public synchronized final int Putcount () {return putcount; } public synchronized final int Evictioncount () {return evictioncount; } public synchronized final map<k, v> snapshot () {return new linkedhashmap<k, v> (MAP); }}
LruCache use
Let's take a look at two diagrams of memory usage
图-1
图-2
The above analysis of the memory analysis is the same application data, the only difference is that figure 1 does not use LruCache, and figure 2 used LruCache; it can be very obvious to see that figure 1 of the memory use is significantly larger, basically is around 30M, The memory usage of Figure 2 is basically around 20M. This saves nearly 10M of memory!
OK, the implementation code is posted below
/** * Created by Gyzhong on 15/4/5. */public class Lrupageadapter extends Pageradapter {private list<string> mdata; Private lrucache<string,bitmap> Mlrucache; private int mtotalsize = (int) runtime.getruntime (). TotalMemory (); Private Viewpager Mviewpager; Public Lrupageadapter (Viewpager viewpager,list<string> data) {mdata = data; Mviewpager = Viewpager; /* Instantiate lrucache*/Mlrucache = new Lrucache<string,bitmap> (MTOTALSIZE/5) {/* when the cache is larger than the maximum value we set, this method is called and we Can be used to do memory release operations */@Override protected void Entryremoved (Boolean evicted, String key, Bitmap OldValue, Bi TMap newvalue) {super.entryremoved (evicted, Key, OldValue, NewValue); if (evicted && oldValue! = null) {oldvalue.recycle (); }}/* Create bitmap*/@Override protected bitmap created (String key) { Final int resId = Mviewpager.getresources (). Getidentifier (Key, "drawable", Mviewpager.getcontext (). Getpackagename ()) ; Return Bitmapfactory.decoderesource (Mviewpager.getresources (), resId); }/* Gets the size of each value */@Override protected int sizeOf (String key, Bitmap value) { return Value.getbytecount (); } } ; } @Override Public Object instantiateitem (viewgroup container, int position) {View view = Layoutinflater.fro M (Container.getcontext ()). Inflate (R.layout.view_pager_item, NULL); ImageView ImageView = (ImageView) View.findviewbyid (R.id.id_view_pager_item); Bitmap Bitmap = Mlrucache.get (mdata.get (position)); Imageview.setimagebitmap (bitmap); Container.addview (view); return view; } @Override public void Destroyitem (ViewGroup container, int position, object object) {Container.removeview ( (View) object); } @Override Public int GetCount () {return mdata.size (); } @Override Public Boolean isviewfromobject (view view, Object object) {return view = = Object; }}
Summarize
1, LruCache is a caching mechanism based on LRU algorithm;
2, the LRU algorithm principle is to remove the least recently used data, of course, the premise is that the current amount of data is greater than the maximum value set.
3, LruCache does not really release memory, just remove the data from the map, the actual release of memory or the user to manually release.
Demo Source Download
Original address: http://blog.csdn.net/jxxfzgy/article/details/44885623
LRUCache Detailed Android Memory optimizer