LRU (Least recently used) least recently used algorithm
Principle
The cache holds a strong reference (starting with Android 2.3, the garbage collector is more inclined to reclaim weak and soft references, soft references and weak references become unreliable, and in Android 3.0, the picture's data is stored in local memory and therefore cannot be released in a predictable way) to limit the number of values. Whenever a value is accessed, it is moved to the head of the queue. When a new value is added when the cache is full, the last value in the queue is out of line and may be recycled
LRUCache internal maintenance is mainly achieved through LINKEDHASHMAP
This is a secure thread, and the multithreaded cache is implemented synchronously?
Use
By default, the size of the cache is determined by the number of values, and rewriting sizeof calculates different values
If your cache value needs to be explicitly released, rewrite entryremoved ()
int maxMemory = (int) Runtime.getRuntime().maxMemory(); int8; //给LruCache分配1/8 4M new LruCache<String, Bitmap>(mCacheSize){ //必须重写此方法,来测量Bitmap的大小 @Override protectedintsizeOfvalue) { returnvaluevalue.getHeight(); } };
Mmemorycache.put (key, bitmap)
Mmemorycache.get (Key)
This class is not allowed to have null key values. Get,put,remove return null value, key corresponding value is not in cache
SOURCE Analysis
constructor that initializes the maximum capacity and Linkedhashmap
/** * @param maxSize for caches that does not override {@link #sizeOf}, this is * the maximum Numbe R of entries in the cache. For any other caches, * this is the maximum sum of the sizes of the entries in this cache. */ Public LruCache(intMaxSize) {if(MaxSize <=0) {Throw NewIllegalArgumentException ("maxSize <= 0"); } This. maxSize = maxSize; This. Map =NewLinkedhashmap<k, V> (0,0.75Ftrue); }
This sets the Linkedhashmap last parameter (Accessorder) to true, and when the Accessorder is set to true, the traversal order and the access order are consistent. Its internal doubly linked list will arrange entry objects in the order of least recent access to the most recent visits
Put method, first does not allow the key value is empty, then is thread safety, put the number of times plus one, size increase, in the form of key-value pairs to deposit linkedhashmap, if the previous existence of this key value pair, size reduced to the original sizes, if the capacity exceeds maxsize, The entry that are rarely accessed recently will be deleted
/** * Caches {@code value} for {@code key}. The value is moved to the head of * the queue. * * @return The previous value mapped by {@code key}. */Public final V put (K key, V value) { if (key = = NULL | | value = = NULL) { throw new NullPointerException ("Ke y = = 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; }
The Put method has a key point where exceeding the maximum value is to delete the least recently accessed
TrimToSize first thread-safe, check whether the current size is greater than the maximum value, if it is greater than the maximum, remove the least recently (the loop to delete the list header Element) is accessed by the element, get the key value, delete
/** * Remove the eldest entries until the total of remaining entries are at or * below the requested size. * * @param maxSize The maximum size of the cache before returning. May be-1 * To evict even 0-sized elements. */ Public void TrimToSize(intMaxSize) { while(true) {K key; V value;synchronized( This) {if(Size <0|| (Map.isempty () && Size! =0)) {Throw NewIllegalStateException (GetClass (). GetName () +". SizeOf () is reporting inconsistent results!"); }if(Size <= maxSize) { Break; } map.entry<k, v> toevict = Map.eldest ();if(Toevict = =NULL) { Break; } key = Toevict.getkey (); Value = Toevict.getvalue (); Map.Remove (key); Size-= safesizeof (key, value); evictioncount++; } entryremoved (true, key, Value,NULL); } }
Get method, first key cannot be empty, thread safe, according to key, get value from Linkedhashmap, not empty words return, empty words, create a key, create failure return null, create success, create key value pair in Linkedhashmap, exists on overwrite, no size increase, return value value
/** * Returns The value for {@code key} If it is exists in the cache or can being * created by {@code #create}. If A value was returned, it's moved to the * head of the queue. This returns null if a value is not cached and cannot * be created. */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++; }/* * 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. */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 {size + safesizeof (key, Createdvalue); }} if (Mapvalue! = null) {entryremoved (False, Key, Createdvalue, Mapvalue); return mapvalue; } else {trimtosize (maxSize); return createdvalue; } }
Core code analysis finished, want to know Linkedhashmap, please listen to the next beep beep
Note: This article source from API 23
Android LRUCache parsing